我有一个布局如下的 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/