简体   繁体   中英

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. 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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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