Given a data frame df
with just one variable v4
with four observations, I can manually mutate the three variables I want (see below). But how can I generalize the problem? For example, if the data frame has 10 rows, the number of columns will be 9.
library(dplyr)
# Toy Data
df <- tibble(v4 = c(20, 10, 8, 0))
df
#> # A tibble: 4 × 1
#> v4
#> <dbl>
#> 1 20
#> 2 10
#> 3 8
#> 4 0
# Constants
u <- .6
d <- .4
r <- 1.1
# df_wanted, done manually
df_wanted <- df %>%
mutate(v3 = (u * lag(v4) + d * v4 )/ r,
v2 = (u * lag(v3) + d * v3)/ r,
v1 = (u * lag(v2) + d * v2 )/ r)
df_wanted
#> # A tibble: 4 × 4
#> v4 v3 v2 v1
#> <dbl> <dbl> <dbl> <dbl>
#> 1 20 NA NA NA
#> 2 10 14.5 NA NA
#> 3 8 8.36 11.0 NA
#> 4 0 4.36 6.15 8.22
Created on 2022-12-01 with reprex v2.0.2