我的data.table(包:data.table
)如下所示:
set.seed(1)
data <- data.table(time =c(1:3,1:4),groups = c(rep(c("b","a"),c(3,4))), value = rnorm(7))
groups time value
1: b 1 -0.6264538
2: b 2 0.1836433
3: b 3 -0.8356286
4: a 1 1.5952808
5: a 2 0.3295078
6: a 3 -0.8204684
7: a 4 0.4874291
我希望能够将值列滞后多个值。下面是如果值滞后2的输出示例(但是滞后量应该任意设置):
groups time value lag.value
1 a 1 1.5952808 NA
2 a 2 0.3295078 NA
3 a 3 -0.8204684 1.5952808
4 a 4 0.4874291 0.3295078
5 b 1 -0.6264538 NA
6 b 2 0.1836433 NA
7 b 3 -0.8356286 -0.6264538
请告知
编辑:此问题的发布是为了详细说明已发布的答案here