Hi, RStudio community!
I've been working super hard on a dplyr problem. My goal is to compute a variable (column) based on the lagged values of such a column. The first value is given (in this example it's 100). The goal is to "imitate" the behavior of this spreadsheet:
-
value starts at 100 in cell D2.

-
cell D3 (i.e. next value) is calculated based on the value on D2...

-
cell D4 is calculated based on the value on D3, and so on...

Here's a reprex with an example tibble (my_tbl) and the tibble that I want to get (target_tbl). The last piece of code has my (failed) attempt:
library(tidyverse)
# --- A toy input ---
my_tbl <- tibble(
x = c(43.9375, 44.25, 44.3437),
y = c(0, 50, 0),
r = x / lag(x) - 1
)
# --- The output I wish to generate ---
target_tbl <- tibble(
x = c(43.9375, 44.25, 44.3437),
y = c(0, 50, 0),
r = x / lag(x) - 1,
value = c(100, 216.53, 216.99)
)
# --- Define n ---
n <- 2
# --- Attempt ---
my_attempt <- my_tbl %>%
rowwise() %>%
mutate(value = if_else(condition = is.na(lag(x)),
true = 100,
false = (lag(value) + y * n) * (1+r))
)
#> Error: Problem with `mutate()` input `value`.
#> x object 'value' not found
#> i Input `value` is `if_else(...)`.
#> i The error occurred in row 1.
Created on 2020-10-25 by the reprex package (v0.3.0)
Is this one of those cases where I HAVE to do it with a for-loop? 
Thank you very much in advance!
Best,
Alexis