使用dplyr进行条件减法的累积和

时间:2022-02-20 08:49:18

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.

我正在尝试使用R中的dplyr包来计算条件累积和。我正在构建一个带有负冲击的储蓄计算器。所以我想要一个累积节省的变量,减去冲击。这似乎应该是使用滞后函数相当简单,但我似乎无法让它工作。

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.

理想情况下,我想让负储蓄冲击只是积累的储蓄的一小部分,但我想我会从一个更简单的案例开始。

1 个解决方案

#1


2  

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

#1


2  

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