本文介绍了在 R data.table 计算中使用前一行的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 data.table 中创建一个新列,该列是根据一列的当前值和另一列的前一个值计算得出的.是否可以访问以前的行?
例如:
>DT
正确答案应该是
>DTA B C D1:1 10 100 不适用2:2 20 200 2103:3 30 300 3204:4 40 400 4305:5 50 500 540
解决方案
在 ,这很简单.
DT[ , D := C + shift(B, 1L, type="lag")]# 或者等效地,在这种情况下,DT[ , D := C + shift(B)]
来自 新闻:
- 新函数
shift()
实现vector、list、data的快速lead/lag
.frames 或 data.tables.它需要一个type
参数,该参数可以是 "lag"(默认)或 "lead".它与:=
或set()
一起使用非常方便.例如:DT[, (cols) := shift(.SD, 1L), by=id]
.请查看?shift
了解更多信息.
查看历史以获取以前的答案.
I want to create a new column in a data.table calculated from the current value of one column and the previous of another. Is it possible to access previous rows?
E.g.:
> DT <- data.table(A=1:5, B=1:5*10, C=1:5*100)
> DT
A B C
1: 1 10 100
2: 2 20 200
3: 3 30 300
4: 4 40 400
5: 5 50 500
> DT[, D := C + BPreviousRow] # What is the correct code here?
The correct answer should be
> DT
A B C D
1: 1 10 100 NA
2: 2 20 200 210
3: 3 30 300 320
4: 4 40 400 430
5: 5 50 500 540
解决方案
With shift()
implemented in v1.9.6, this is quite straightforward.
DT[ , D := C + shift(B, 1L, type="lag")]
# or equivalently, in this case,
DT[ , D := C + shift(B)]
From NEWS:
See history for previous answers.
这篇关于在 R data.table 计算中使用前一行的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!