I want to create a variable based on a given growth rate, which is in another variable, starting from a base of 1. Below is an example. I tried two methods, either applying growth rate to lagged value or compound formula for the case of constant growth rate). None of the method works.
Note: For simplicity, growth rate is constant at 10%, but that is not the case of my data. (Could use for instance growth rate of variable in data, with diff(data)/lag(data))
Update: added target result as variable
library(xts)
data <- as.xts(AirPassengers)
gr <- 0.1 # 10% growth
data <- cbind(data,gr)
# Method 1, based on lag
data$v2 <- 1
data$v2 <- lag(data$v2)*(1+data$gr)
# Method 2, based on compound growth formula
data$v3 <- 1
data$v3 <- first(data$v3)*(1+data$gr)^(index(data$gr))
data$target <- 1*1.1^(1:144) # vector growing 10%, starting at 1
What is it that I'm doing wrong? Can't work it out from vignette or other help online.
Here are two ways.
The first uses a
forloop in order to make the calculations being performed more clear. The main problem is to coerce the data indatato numeric values.Created on 2023-11-28 with reprex v2.0.2
The second way uses a
dplyrpipe to produce the same vectorv2. And then computes a vectorv3from the growth rates given by thedatacolumn's variations.Created on 2023-11-28 with reprex v2.0.2
Edit
What follows is not the best example to illustrate my comment but it is based on what seems to be one of the question's problems.
Created on 2023-11-29 with reprex v2.0.2