I have a numeric vector like this x <- c(1, 23, 7, 10, 9, 2, 4)
and I want to group the elements from left to right with the constrain that each group sum must not exceed 25
. Thus, here the first group is c(1, 23)
, the second is c(7, 10)
and the last c(9, 2, 4)
. the expected output is a dataframe with a second column containing the groups:
data.frame(x= c(1, 23, 7, 10, 9, 2, 4), group= c(1, 1, 2, 2, 3, 3, 3))
I have tried different things with cumsum
but am not able to kind of dynamically restart cumsum for the new group once the limit sum of 25
for the last group is reached.