用于基于累积倍数约束/组的循环/替换值

时间:2016-07-19 09:42:22

标签: r for-loop data.table dplyr

按照我之前对任何人都不清楚的问题。我想出了一个新的可重现的例子

我在R

中有以下INPUT数据帧
DF.IN <- data.frame(
  "Product"= c("X1","X2","X3","X4","X5","X6"),
  "G1"= c("RC1","RC1","RC2","RC2","RC1","RC1"),
  "G2"= c("IN1","IN2","IN1","IN1","IN1","IN2"),
  "MAX.G1"= c("18","18","8","8","18","18"),
  "MAX.G2"= c("20","60","20","20","20","60"),
  "Amount"= c("10","5","3","6","15","1"),
  stringsAsFactors = FALSE
  )

给出

  Product  G1  G2 MAX.G1 MAX.G2 Amount
  X1       RC1 IN1  18     20     10
  X2       RC1 IN2  18     60      5
  X3       RC2 IN1   8     20      3
  X4       RC2 IN1   8     20      6
  X5       RC1 IN1  18     20     15
  X6       RC1 IN2  18     60      1

,其中

  • G1和G2 =第1组&amp;第2组
  • Max.G1和Max.G2 =分别为G1和G2的最大允许量

如果我们计算每个组的累计金额,例如

DF.IN[, CumSum.G1 := cumsum(Amount), by = list(G1)]
DF.IN[, CumSum.G2 := cumsum(Amount), by = list(G2)]

我们将得到以下结果

   Product  G1  G2 MAX.G1 MAX.G2 Amount CumSum.G1 CumSum.G2
    X1      RC1 IN1     18     20     10        10        10
    X2      RC1 IN2     18     60      5        15         5
    X3      RC2 IN1      8     20      3         3        13
    X4      RC2 IN1      8     20      6         9        19
    X5      RC1 IN1     18     20     15        30        34
    X6      RC1 IN2     18     60      1        31         6

我正在寻找的是 - 对于每个product - 相关Amount,其中Cumulative Amount尊重每个群组允许的最大金额G1&amp;同时G2

所以所需的OUTPUT就是这样的

   Product  G1  G2 MAX.G1 MAX.G2 Amount.EXPECTED CumSum.G1 CumSum.G2
     X1     RC1 IN1     18     20       10        10        10
     X2     RC1 IN2     18     60        5        15         5
     X3     RC2 IN1      8     20        3         3        13
     X4     RC2 IN1      8     20        5         8        18
     X5     RC1 IN1     18     20        2        17        20
     X6     RC1 IN2     18     60        0        17         5

有人可以帮我解决这个问题吗?非常感谢!!

0 个答案:

没有答案