Hi,
I would like advice about the best way to approach row-wise iteration where the value of a variable at row n is dependent on the value at row n-1. I would prefer solutions that use dplyr and/or purrr. I've struggled with this for years, getting by on a mix of for loops, purrrlyr::by_row(), sometimes purrr::pmap, etc. but I've never quite felt I've settled on a good solution.
Here's an example that returns the desired output, in a horrible clunky for-loop-y way.
library(tidyverse)
x <- tibble(a = c(1:10),
b = c(seq(100, 140, 10), rep(NA_real_, 5)) )
fill_in <- function(x, growth = 0.03) {
x <- if_else(!is.na(x), x, lag(x, 1) * (1 + growth))
x
}
for(i in 1:nrow(x)) {
x <- x %>%
mutate(b = fill_in(b))
}
What is the best way to do this? I've read the discussion here and here and have read Jenny Bryan's row-wise slide deck and Winston Chang's blog post and am still not clear. Thank you.