I have a df like this
a b
1 3
2 3
3 3
4 3
1 3
2 3
3 3
4 3
I want the solution like this. I want the moving sum of column 'a' for the 3 intersections which is the value from column b. Values of column b can change.
Result
a b CumSum
1 3 1
2 3 3
3 3 6
4 3 9
1 3 8
2 3 7
3 3 6
4 3 9
below is the code I am using
df$cum_sum <- ave(a,
(seq_along(a)-1)%/%
b,
FUN= cumsum)
but this restarts the cumulative sum on the 4th observation which is not the expected result.