<分区>
R
的 data.table
中的 shift
非常适合时间序列和时间窗口内容。但是列表的列不会像其他元素的列那样滞后。在下面的代码中,gearLag
正确地超前/滞后于 gear
,但是 gearsListLag
并不落后于 gearsList
,相反, shift
在 gearsList
中运行,使同一行中的元素滞后于自身。
dt <- data.table(mtcars)[,.(gear, carb, cyl)]
### Make col of lists
dt[,carbList:=list(list(unique(carb))), by=.(cyl, gear)]
### Now I want to lag/lead col of lists
dt[,.(carb, carbLag=shift(carb)
, carbList, carbListLag=shift(carbList, type="lead")), by=cyl]
cyl carb carbLag carbList carbListLag
1: 6 4 NA 4 NA
2: 6 4 4 4 NA
3: 6 1 4 1 NA <-- should be 4 here, not NA
4: 6 1 1 1 NA
5: 6 4 1 4 NA
6: 6 4 4 4 NA
7: 6 6 4 6 NA
8: 4 1 NA 1,2 2,NA
9: 4 2 1 1,2 2,NA
10: 4 2 2 1,2 2,NA
11: 4 1 2 1,2 2,NA
12: 4 2 1 1,2 2,NA
13: 4 1 2 1,2 2,NA
14: 4 1 1 1 NA <-- should be (1,2) here, not NA
15: 4 1 1 1,2 2,NA
16: 4 2 1 2 NA
17: 4 2 2 2 NA
18: 4 2 2 1,2 2,NA
19: 8 2 NA 2,4,3 4, 3,NA
20: 8 4 2 2,4,3 4, 3,NA
21: 8 3 4 2,4,3 4, 3,NA
22: 8 3 3 2,4,3 4, 3,NA
23: 8 3 3 2,4,3 4, 3,NA
有什么建议可以像我滞后于其他元素一样滞后于列表吗?