rdplyrpurrrrolling-computationaccumulate

From growth rate to series in r dataframe


I’m working in R and want to “recover” a series from growth rates: I have a dataframe with two columns, date and growth_rates.

date     growth_rate
1946-10-01 NA
1947-01-01 3.5
1947-04-01 2.1
1947-07-01 1.6

The growth rate has been calculated in the following way:

growth_rate_t = 400 * (ln(x_t) - ln(x_{t-1}))

I want to add a column with the series x, starting from 100. Basically:

date     growth_rate x
1946-10-01 NA        100
1947-01-01 3.5.      100.88
1947-04-01 2.1       101.41
1947-07-01 1.6       101.82

How can I do this without using a loop?

I have no clue how to do this without a loop.


Solution

  • You can do this:

    library(dplyr)
    library(purrr)
    
    df %>%
      mutate(x = accumulate(2:nrow(df), 
                            ~ exp((growth_rate[.y] + (400 * log(.x))) / 400), .init = 100))
    
            date growth_rate        x
    1 1946-10-01          NA 100.0000
    2 1947-01-01         3.5 100.8788
    3 1947-04-01         2.1 101.4098
    4 1947-07-01         1.6 101.8163