Reputation: 833
I am trying to calculate a conditional cumulative sum using the dplyr package in R. I am building a savings calculator with negative shocks. So I want a variable that has cumulative savings, minus the shocks. This seems like it should be fairly straightforward using the lag function, but I can't seem to get it to work.
Here is an example:
event <- c(0,0,0,1,0)
save <- rep(.5,5)
## add up the savings from each prior row, then when event is one subtract 1
output_want <- c(.5,1,1.5,1,1.5)
df <- tibble(event,save,output_want) %>%
mutate(totsave = if_else(row_number() ==1, save, 0)) %>%
mutate(totsave = if_else(row_number() !=1, save+lag(totsave)-event, save))
Ideally I would like to make the negative savings shock be a fraction of the accumulated savings, but thought I'd start with a simpler case.
Upvotes: 1
Views: 712
Reputation: 44320
If at each time step you want to add the savings from the save
vector but subtract the shock from event
, then you can compute the desired result by taking the cumulative sum of save-event
:
cumsum(save-event)
# [1] 0.5 1.0 1.5 1.0 1.5
Upvotes: 2