I would like to create a column in my df which would calculate the cumsum according to the id. But when the id changes the sum has to reset to the base value for the given id. So I would like to have something like this:
id payment month year cumultative_sum
1 100 01 2015 100
1 150 02 2015 250
1 50 03 2015 300
2 75 07 2016 75
2 125 08 2016 200
Right now with my code the cumultative sum keeps adding further instances even if the id changes so it looks like this:
id payment month year cumultative_sum
1 100 01 2015 100
1 150 02 2015 250
1 50 03 2015 300
2 75 07 2016 375
2 125 08 2016 500
This is my code:
df_ag <- df %>%
group_by(id) %>%
arrange(id, year, month) %>%
mutate(cumultative_sum = cumsum(payment))
What should I change?