R获取当前列的下一个值

R getting the next value of current column

我有一个 data.table 喜欢:

DT = data.table(ColumnA = c(1.51, 1.86, 3.54, 3.79, 7.7))

我正在尝试创建 ColumnB,它包含 ColumnA 的下一个值:

    columnA      ColumnB  

     1.51          1.86
     1.86          3.54   
     3.54          3.79
     3.79          7.70
     7.70

我尝试了以下方法并且它工作正常,但现在它不工作了:

          ``` DT[, ColumnB:=c(NA,ColumnA[.I + 2]) ]```

我收到此错误:

Error in .Call() : Supplied 18391 items to be assigned to 18390 items of column 'ColumnB'. If you wish to 'recycle' the RHS please use rep() to make this intent clear to readers of your code.

看起来您正在编写 data.table 代码,所以您很幸运! shift 函数就是您所追求的:

DT[ , ColumnB := shift(ColumnA, type = 'lead')]

由于您正在使用 shift 进行一些分析,因此请务必查看 data.table 必须提供的其他相关函数:nafillfrollsum/frollmean/froll

至于为什么你的代码不起作用:

c(NA, ColumnA[.I + 2])

第一个元素是NA;接下来是索引 .I+2ColumnA 的向量子集。 .I + 2.I 的所有元素,向上移动了 2.IColumnA 具有相同的长度,因此 ColumnA[.I + 2] 也将具有与 ColumnA 相同的长度 - 因此 c(NA, ColumnA[.I + 2]) 具有更多 元素比 ColumnA.

这就是为什么您会在错误中看到差一的注释:

Supplied 18391 items to be assigned to 18390 items

如果你想做一个子集方法(这会更慢),你可以这样做:

DT[ , ColumnA := c(NA, ColumnA[-1L])]

ColumnA[-1L]ColumnA, minus first 元素,因此元素比在 ColumnA 中,当我们与 NA 结合时,我们得到了正确的数字。