Search code examples
rdplyreconomics

How to mutate without overwriting existing data in data frame?


Below is the example data frame that I will be using. The difference column stands for price difference in time. For example, the price prediction in 2001 will be 6 + 3 = 9

time difference price
2000 NA 6
2001 3 NA
2002 4 NA
2003 6 NA
2004 -8 NA

Right now the code that I am using is below and it is not working since if I were to loop it, it would overwrite previous data when even I do so.

Data <- Data %>%
  mutate(new_price = difference + lag(new_price))

What I am looking for the a piece of code that can finish the list in one click, such that the expecting result would be

time difference price
2000 NA 6
2001 3 9
2002 4 13
2003 6 19
2004 -8 11

Any solution is welcomed and thank you guys very much.


Solution

  • Please try this

    library(tidyverse)
    dat <- data.frame(time=c(2000,2001,2002,2003,2004,2005), diff=c(NA, 3, 4, 6, -8, 10), price=c(6, NA, NA, NA, NA, NA))
    dat2 <- dat %>% mutate(price=cumsum(coalesce(diff,price)))