使用R中的自引用滞后公式计算列

时间:2018-10-17 20:33:05

标签: r data.table

我正在尝试使用包括我计算出的列在内的几列中的行数滞后来计算一列。实际上,我想要一个自引用累积公式。

一个例子:

library(data.table)
library(lubridate)

dt <- data.table(date = today()+1:10, supply = c(1,1,2,3,1,0,1,2,1,3), demand = c(0,0,1,0,3,2,1,0,1,0), inventory = 0)
          date supply demand inventory
 1: 2018-10-18      1      0         0
 2: 2018-10-19      1      0         0
 3: 2018-10-20      2      1         0
 4: 2018-10-21      3      0         0
 5: 2018-10-22      1      3         0
 6: 2018-10-23      0      2         0
 7: 2018-10-24      1      1         0
 8: 2018-10-25      2      0         0
 9: 2018-10-26      1      1         0
10: 2018-10-27      3      0         0

我要实现的是参考上一时期的库存+供求-需求进行库存计算:

          date supply demand inventory
 1: 2018-10-18      1      0         0
 2: 2018-10-19      1      0         1
 3: 2018-10-20      2      1         2
 4: 2018-10-21      3      0         3
 5: 2018-10-22      1      3         6
 6: 2018-10-23      0      2         4
 7: 2018-10-24      1      1         2
 8: 2018-10-25      2      0         2
 9: 2018-10-26      1      1         4
10: 2018-10-27      3      0         4

但是,当我尝试时:

dt[,inventory := shift(inventory, fill = 0) + shift(supply, fill = 0) - shift(demand, fill = 0)]

我得到:

          date supply demand inventory
 1: 2018-10-18      1      0         0
 2: 2018-10-19      1      0         1
 3: 2018-10-20      2      1         1
 4: 2018-10-21      3      0         1
 5: 2018-10-22      1      3         3
 6: 2018-10-23      0      2        -2
 7: 2018-10-24      1      1        -2
 8: 2018-10-25      2      0         0
 9: 2018-10-26      1      1         2
10: 2018-10-27      3      0         0

因为移位是指以前存储的数字,而不是新计算的数字。

我可以使用循环来解决此问题,但它作为一种优雅的解决方案并不吸引我。还有其他方法可以到达那里吗?

1 个答案:

答案 0 :(得分:1)

好吧,我想我已经找到一种“欺骗”的方式来解决它:

dt[,':=' (cum_supply = cumsum(supply), cum_demand = cumsum(demand))]
dt[,inventory := dt[date==today()+1,inventory] + shift(cum_supply,fill = 0) - shift(cum_demand,fill = 0)]

但是,如果有人可以提出更优雅的解决方案,我很乐意看到它!