r data.table - 我们可以在新创建的列上使用 shift()

r data.table - can we use shift() on newly created columns

是否可以在新创建的列上使用 shift?在 for 循环编程中,我们可以从上一行访问新列的值。例如如下所示...我在 shift 语句中出现错误,因为即使应该计算出“c”,“c”也不存在。

x <- data.table(a=c(1,2,3), b=c(4,5,6))
x[,':='(c=a*b, d=shift(c,-1))]

一种可能的解决方案是在 {}:

内计算 cd
x <- data.table(a=c(1,2,3), b=c(4,5,6))

x[,c("c","d"):=({c=a*b; d=shift(c,-1); list(c,d)})][]

   a b  c  d
1: 1 4  4 10
2: 2 5 10 18
3: 3 6 18 NA