使用R data.table计算中上一行的值 [英] Use a value from the previous row in an R data.table calculation
本文介绍了使用R data.table计算中上一行的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在data.table中创建一个新列,该列是从一列的当前值和另一列的前一个列计算而来的。是否可以访问以前的行?
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?
例如:
> 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?
正确的答案应该是
> 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
推荐答案
c> shift()在 v1.9.6 中实施,这是相当直接。
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)]
从新闻:
- 新功能
shift / code>实现向量,列表,的快速
超前/滞后
/ em>或 data.tables 。它需要一个类型
参数,可以是lag(默认)或lead。它与:=
或set()
非常方便地使用。例如:DT [,(cols):= shift(.SD,1L),by = id]
。请查看?shift
了解详情。
- New function
shift()
implements fastlead/lag
of vector, list, data.frames or data.tables. It takes atype
argument which can be either "lag" (default) or "lead". It enables very convenient usage along with:=
orset()
. For example:DT[, (cols) := shift(.SD, 1L), by=id]
. Please have a look at?shift
for more info.
查看上一个答案的历史记录。
See history for previous answers.
这篇关于使用R data.table计算中上一行的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文