我是data.table的初学者。任何人都可以向我解释为什么我不能用shift()
得到预期的结果? (我用“领先”或“滞后”获得相同的结果)
set.seed(123)
x <- data.table(a = sample(1:10,10,replace = F))
x <- x[order(a)][, a1 := shift(a,1,"lead")]
x
a a1
1: 1 NA
2: 2 1
3: 3 2
4: 4 3
5: 5 4
6: 6 5
7: 7 6
8: 8 7
9: 9 8
10: 10 9
以下是我期待的结果:
data.table(a = 1:10, a1 = c(2:10,NA))
a a1
1: 1 2
2: 2 3
3: 3 4
4: 4 5
5: 5 6
6: 6 7
7: 7 8
8: 8 9
9: 9 10
10: 10 NA
答案 0 :(得分:6)
shift
的功能定义是
shift(x, n=1L, fill=NA, type=c("lag", "lead"), give.names=FALSE)
但是,由于您还没有指定您正在使用的参数,因此该函数假定您的第三个参数用于fill
参数(定义中的第三个参数)。
所以你真正做的是
shift(x = a, n = 1, fill = "lead", type = "lag", give.names = FALSE)
## where type & give.names are using their default values
您可能希望明确说明参数:
set.seed(123)
library(data.table)
x <- data.table(a = sample(1:10,10,replace = F))
x[order(a)][, a1 := shift(a, n = 1, type = "lead")][]
# a a1
# 1: 1 2
# 2: 2 3
# 3: 3 4
# 4: 4 5
# 5: 5 6
# 6: 6 7
# 7: 7 8
# 8: 8 9
# 9: 9 10
# 10: 10 NA