简体   繁体   English

R data.table选择组块中的上一行

[英]R data.table selecting the previous row within group blocks

I have the following example data frame. 我有以下示例数据框。

id value
a  3
a  4
a  8
b  9
b  8

I want to convert it so that I can calculate differences in the column "value" between successive rows. 我想转换它,以便我可以计算连续行之间的“值”列的差异。 So the expected result is 所以预期的结果是

id value prevValue
a   3     0
a   4     3
a   8     4
b   9     0
b   8     9

Notice within each group I want the sequence of values to start with a 0 and successive values are from the one prior. 请注意,在每个组中,我希望值序列以0开头,连续值来自前一个值。 I tried the following 我尝试了以下内容

x = x[,list(
prevValue = c(0,value[1:(.N-1)])
),by=id]

but no luck. 但没有运气。 Thanks in advance. 提前致谢。

使用负索引,例如:

x[,prev.value := c(0,value[-.N]) ,by=id]

Without data.table : 没有data.table

with(dat,ave(value,id,FUN=function(x) c(0,head(x,-1))))
[1] 0 3 4 0 9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM