I am trying to follow a process where I make a contribution to an investment every period, that investment grows or shrinks over time and then I have an ending balance. The next period I take that ending balance, add the next period’s contribution and invest again. The process repeats from there.
In table form this would be shown as
So the 105 is the 100 * 1.05, the 205 is the 100+105 which is then multiplied by 0.95 to get 194.75. The 304.75 is the 194.75+110, etc.
This is easy to do in a spreadsheet, but pretty tricky in R. I tried
df <- df %>%
mutate(Return = ifelse(is.na(lag(Contribution,
Contribution*Grow,
(lag(Contribution)*lag(Grow)*Grow)+(Contribution*Grow)
))))
But I got the error message
Error in
mutate(): ℹ In argument:Return = ifelse(...). Caused by error inlag(): !nmust be a whole number, not a double vector. Runrlang::last_trace()to see where the error occurred.
Below is the data.
df <- data.frame(Contribution=c(100,100,110,110),Grow=c(1.05,0.95,1.1,0.925))
I tried the code shown and the expectation is in the table.
