I need to create several amortization tables. I did it, but it takes a lot because there are a lot of data. As you know R is not good with for loops, so im trying to optimize the time invested in that operation.
I have the for loop and it works
for (i in 1:nrow(df)) {
if (df[i,"aux"]== 1) {
df[i,"Interest"] <-df[i,"Original_mount"] * df[i,"MonthlyRate"]
df[i,"Capital"] <- df[i,"instalement"]-df[i,"Interest"]
df[i,"final_balance"]<-df[i,"inicial_balance"] - df[i,"Capital"]
} else {
df[i,"inicial_balance"]<-df[i-1,"final_balance"]
df[i,"Interest"] <-df[i,"inicial_balance"] * df[i,"MonthlyRate"]
df[i,"Capital"] <- df[i,"instalement"]-df[i,"Interest"]
df[i,"final_balance"]<-df[i,"inicial_balance"] - df[i,"Capital"]
and i try mutate, apply, purr and nothing works.
Mutate: because is an iterative process and mutate make all the column apply: because the output is a list Purrr: all the output is NA
Do you have any experience with this?
You can use known formulas for
installment: ( A * [( i * (1 + i)^n) / ((1 + i)^n - 1)]),
the first capital payment: (P_1= A * i /((1 + i)^n - 1)),
and the subsequent capital payments: (P_n = P_{n-1} * (1 + i))
This reduzes time and avoid the loop. Try this:
Using library(microbenchmark). I call your procedure "proc1" and this alternative "proc2". The improvement is very clear!