Conditional cumsum with reset

后端 未结 4 1394
暗喜
暗喜 2020-12-03 01:54

I have a data frame, the data frame is already sorted as needed, but now I will like to \"slice it\" in groups.

This groups should have a max cumulative value of 10

4条回答
  •  自闭症患者
    2020-12-03 02:35

    We can take advantage of the function cumsumbinning, from the package MESS, that performs this task:

    library(MESS)
    df %>%
      group_by(group_10 = cumsumbinning(value, 10)) %>%
      mutate(cumsum_10 = cumsum(value)) 
    

    Output

    # A tibble: 15 x 5
    # Groups:   group_10 [7]
          id order value group_10 cumsum_10
                  
     1     6     1     4        1         4
     2    10     2     5        1         9
     3     1     3     7        2         7
     4     5     4     3        2        10
     5     3     5     8        3         8
     6     9     6     1        3         9
     7    14     7     2        4         2
     8    11     8     5        4         7
     9    15     9     3        4        10
    10     8    10     6        5         6
    11    12    11     2        5         8
    12     2    12     6        6         6
    13     4    13     3        6         9
    14     7    14     1        6        10
    15    13    15     4        7         4
    

提交回复
热议问题