r - 如何在 R 中的 data.table 中使用具有累积值的移位计算

标签 r data.table shift

我有一个布局如下的 data.table

TestData <- data.table(Threshold = 20,
                       Upto = 100,
                       Demand = c(0,0,5,0,50,10,10,10,10,50,20,60),
                       Stock  = c(100,0,0,0,0,0,0,0,0,0,0,0))

股票值(value)应计算为累积值,公式为:

If Stock (previous row) minus Demand (current row) is less or equal than the threshold, than update the current cell in Stock with the value in "Upto". Else update the value of stock (current row) with stock (previous row) minus demand (current row).

然后程序应该重新开始。结果应如下所示:

TestData <- data.table(Threshold = 20,
                       Upto = 100,
                       Demand = c(0,0,5,0,50,10,10,10,10,50,20,60),
                       Stock = c(100,100,95,95,45,35,25,100,90,40,100,40))

    Threshold Upto Demand Stock
 1:        20  100      0   100
 2:        20  100      0   100
 3:        20  100      5    95
 4:        20  100      0    95
 5:        20  100     50    45
 6:        20  100     10    35
 7:        20  100     10    25
 8:        20  100     10   100
 9:        20  100     10    90
10:        20  100     50    40
11:        20  100     20   100
12:        20  100     60    40

我所做的如下:

TestData[, Stock:= ifelse(cumsum(shift(Stock, 0, type="lead") - Demand) <= Threshold,
                     Upto,
                     cumsum(shift(Stock, 0, type="lead") - Demand))]

但在第一次更新后,计算停止并显示 100 每次平铺结束。库存中的第一个值是我手动设置的初始值。谢谢!

最佳答案

这是一个 data.table 解决方案。创新在于 by 分组。请务必发布此解决方案失败的任何边界案例。

TestData <- data.table(Threshold = 20,
                       Upto = 100,
                       Demand = c(0,0,5,0,50,10,10,10,10,50,20,60),
                       Stock  = c(100,0,0,0,0,0,0,0,0,0,0,0))

#to see by grouping
#TestData[,trunc(cumsum(Demand)/(Threshold - Upto))]

TestData[, Stock2 := c(Upto[1], Upto[1] - cumsum(Demand[-1])),
    by=trunc(cumsum(Demand)/(Threshold - Upto))]
TestData

关于r - 如何在 R 中的 data.table 中使用具有累积值的移位计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43372937/

相关文章:

regex - 捕获组中带有贪婪修饰符的奇怪行为

r - ggplot2 中的水平滑动条形图

r - data.table lapply .SD 随着列数的增加而大幅减慢

r - 合并具有重叠值的行

algorithm - Matlab:删除矩阵的冗余 "shifted"条目

python - 从共同作者数据创建边缘列表

r - stringr 相当于 grep

r - 对特定列的 data.table 行求和

javascript - 更改数组中的元素位置并在其间移动元素

c - 向右移动/我做错了什么?