I am trying to create an R loop to help me get Var2, Var3, and Var4 (see output below). Var1, Var5 is pre-entered. Var41 is pre-entered.
Var2 = lag(Var4) * Var5
Var3 = Var2 + lag(Var3)
Var4 = Var1 - Var3
Any suggestions?
I am trying to create an R loop to help me get Var2, Var3, and Var4 (see output below). Var1, Var5 is pre-entered. Var41 is pre-entered.
Var2 = lag(Var4) * Var5
Var3 = Var2 + lag(Var3)
Var4 = Var1 - Var3
Any suggestions?
First I pre-fill the table with initial values:
df <- data.frame(row = 1:5,
Var1 = rep(500, 5),
Var2 = c(0, rep(NA_real_, 4)),
Var3 = c(0, rep(NA_real_, 4)),
Var4 = c(500, rep(NA_real_, 4)),
Var5 = 0.1)
Then, since this is recursive, I rerun this procedure, and each time it fills in one more row based on the availability of the prior row. (Probably not the most elegant, but it works!)
library(dplyr)
for(i in 2:nrow(df)) {
df <- df %>%
mutate(Var2 = if_else(row == 1, 0, lag(Var4) * Var5),
Var3 = if_else(row == 1, 0, Var2 + lag(Var3)),
Var4 = if_else(row == 1, 500, Var1 - Var3),
Var5 = 0.1)
}
Output
> df
row Var1 Var2 Var3 Var4 Var5
1 1 500 0.00 0.00 500.00 0.1
2 2 500 50.00 50.00 450.00 0.1
3 3 500 45.00 95.00 405.00 0.1
4 4 500 40.50 135.50 364.50 0.1
5 5 500 36.45 171.95 328.05 0.1
A base R solution.
We pre-allocate df
with the starting values
df <- data.frame(
Var1 = rep(500, 5),
Var2 = 0,
Var3 = 0,
Var4 = 500,
Var5 = rep(0.1, 5)
)
We note that that we can re-write the recursive relationships as
Var4[i] = Var1[i] - Var4[i-1] * Var5[i] - Var3[i-1]
Var3[i] = Var4[i-1] * Var5[i] + Var3[i-1]
Var2[i] = Var4[i-1] * Var5[i]
We can then replace values in df
within one for
loop
for (i in 2:nrow(df)) {
df$Var4[i] = df$Var1[i] - df$Var4[i-1] * df$Var5[i] - df$Var3[i-1]
df$Var3[i] = df$Var4[i-1] * df$Var5[i] + df$Var3[i-1]
df$Var2[i] = df$Var4[i-1] * df$Var5[i]
}
df
# Var1 Var2 Var3 Var4 Var5
#1 500 0.00 0.00 500.00 0.1
#2 500 50.00 50.00 450.00 0.1
#3 500 45.00 95.00 405.00 0.1
#4 500 40.50 135.50 364.50 0.1
#5 500 36.45 171.95 328.05 0.1