繁体   English   中英

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

[英]How to use a shift calculation with a cumulative value in a data.table in R

我有一个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))

应使用以下公式计算库存值作为累计值:

如果Stock(前一行)减去Demand(当前行)小于或等于阈值,则使用“Upto”中的值更新Stock中的当前单元格。 否则更新库存(当前行)的库存(前一行)减去需求(当前行)。

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

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

如果你能使用循环解决方案。 我不认为这对dplyr(或data.table)是可行的,但我希望有人能证明我错了。

for (i in 2:nrow(TestData)) {
  # If stock - demand <= threshold, restock
  if ((TestData[i-1, "Stock"] - TestData[i, "Demand"]) <= TestData[i, "Threshold"]) 
  {
    TestData[i, "Stock"] <- TestData[i-1, "Upto"]
  }
  # Else update stock with stock - demand
  else 
  {
    TestData[i, "Stock"] <- TestData[i-1, "Stock"] - TestData[i, "Demand"]
  }
}

是一个棘手的问题。 是否有一个do-while原则:

upVal     = 100
threshVal = 20
cumVals   <- TestData$Demand
cumMaster <- cumsum(cumVals) 


repeat{
    IND <- cumMaster>=upVal-threshVal
    cumVals[min(which(IND == TRUE))] <- 0
    cumMaster[IND] <- cumsum(cumVals[IND])
    if(all(cumMaster<upVal-threshVal)){
        break
    }
}

TestData$Stock <- 100 - cumMaster

结果

TestData$Stock

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM