【问题标题】:Dplyr cumsum with constraining column带约束列的 Dplyr cumsum
【发布时间】:2017-07-13 17:28:07
【问题描述】:

我有一个问题,我需要生产一定数量的单位,但有产能限制。 所以我有一个数据框,两列,一列用于我可以构建的容量,每一行是一周,还有一个分配列,这是交易用完的数量。 分配不能大于容量。

请参阅下面的交易金额为 10。

df <- data.frame(capacity = c(2,3,0,1,2,3),
                     allocation = c(0,0,0,0,0,0))

capacity allocation
       2          0
       3          0
       0          0
       1          0
       2          0
       3          0

amount <- 10

dfb <- data.frame(capacity = c(2,3,0,1,2,3),
                      allocation = c(2,3,0,1,2,2))

这就是我想要的结果

capacity allocation
       2          2
       3          3
       0          0
       1          1
       2          2
       3          2

我尝试了以下方法,但它没有给我正确的答案

dfb <- df %>% 
           mutate(deal = 0) %>%
           mutate(deal = if_else(row_number(deal) == 1, amount, 0)) %>%
           mutate(deal = cumsum(deal - pmin(capacity, deal)))

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    分两步分配:

    df %>% 
        # allocate cumulatively and truncate if the total surpass the amount
        mutate(allocation = pmin(cumsum(capacity), amount), 
               # calculate the final allocation based on the cumulative allocation
               allocation = allocation - lag(allocation, default = 0))
    
    #  capacity allocation
    #1        2          2
    #2        3          3
    #3        0          0
    #4        1          1
    #5        2          2
    #6        3          2
    

    【讨论】:

      【解决方案2】:

      这是另一个选择...

      dfb <- df %>% mutate(allocation=pmin(capacity,
                           pmax(0, amount-lag(cumsum(capacity), default = 0))))
      
      dfb
        capacity allocation
      1        2          2
      2        3          3
      3        0          0
      4        1          1
      5        2          2
      6        3          2
      

      【讨论】:

        【解决方案3】:

        类似于@Psidom 的回答,使用基数 R

        df <- data.frame(capacity = c(2,3,0,1,2,3),
                         allocation = c(0,0,0,0,0,0))
        amount <- 10
        
        df$allocation <- diff(pmin(cumsum(c(0, df$capacity)), amount))
        

        结果

        > df
          capacity allocation
        1        2          2
        2        3          3
        3        0          0
        4        1          1
        5        2          2
        6        3          2
        

        【讨论】:

          【解决方案4】:

          这是我的解决方案:

          dfb <- df %>% mutate(deal=ifelse(cumsum(capacity)<amount,capacity,capacity+amount-cumsum(capacity)))
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-09-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-02-01
            • 2017-06-02
            • 2021-06-21
            • 1970-01-01
            相关资源
            最近更新 更多