dplyr / R cumulative sum with reset

前端 未结 2 1992
臣服心动
臣服心动 2020-12-01 22:51

I\'d like to generate cumulative sums with a reset if the \"current\" sum exceeds some threshold, using dplyr. In the below, I want to cumsum over \'a\'.

lib         


        
2条回答
  •  日久生厌
    2020-12-01 23:23

    I think you can use accumulate() here to help. And i've also made a wrapper function to use for different thresholds

    sum_reset_at <- function(thresh) {
      function(x) {
        accumulate(x, ~if_else(.x>=thresh, .y, .x+.y))
      }  
    }
    
    tib %>% mutate(c = sum_reset_at(5)(a))
    #       t     a     c
    #     
    # 1     1     2     2
    # 2     2     3     5
    # 3     3     1     1
    # 4     4     2     3
    # 5     5     2     5
    # 6     6     3     3
    tib %>% mutate(c = sum_reset_at(4)(a))
    #       t     a     c
    #     
    # 1     1     2     2
    # 2     2     3     5
    # 3     3     1     1
    # 4     4     2     3
    # 5     5     2     5
    # 6     6     3     3
    tib %>% mutate(c = sum_reset_at(6)(a))
    #       t     a     c
    #     
    # 1     1     2     2
    # 2     2     3     5
    # 3     3     1     6
    # 4     4     2     2
    # 5     5     2     4
    # 6     6     3     7
    

提交回复
热议问题