[Following on from a question I asked about row-wise iteration where the value of a variable at row n depends on its value at row n-1, asked and answered here]
What approach should I take to a recursive row-wise iteration problem where you have multiple columns you want to fill in, and they are interdependent on one another?
For example, say you have this tibble:
library(tidyverse)
x <- tibble(t = c(1:10),
a = c(seq(100, 140, 10), rep(NA_real_, 5)),
b = c(runif(5), rep(NA_real_, 5)),
c = c(runif(5), rep(NA_real_, 5)))
We want to complete the a, b, and c columns. Where they already have a value, those values should remain. For the rows with NAs, we want to fill them in as follows:
a = lag(a, 1) * (1 + growth)
b = a * lag(b, 1)
c = b * lag(a, 2)
I have a feeling purrr::pmap() is the right approach for this type of multi-column problem, but I cannot get it to do what I want in this case.
I tried with pmap and other avenues but I don't think that a recursive computation as general as this can be achieved by pmap - I'd be happy to see a solution if that is possible. So, after thinking about the problem quite a bit, one (not easy) way is to encode the recursion in functions and then just simply mutate. Sorry for the poorly commented script, but can you please see if it works and does what you would like it to do. Mind you the b column (and c consequently) quickly explodes as it grows exponentially with the values in a which are quite large in this case.
Actually, I think you might be better off sticking to loops