More efficient way to accomplish this loop?

I'm trying to figure out how to more efficiently accomplish the below loop. I have simplified it quite a bit and used basic sample data, which leads to some non-sensical results, but it's the programming technique I'm trying to improve here.

I used a loop in this set of columns because each calculation row depended on the prior results of another row in this set of columns, and I had no idea how to implement that in an efficient way in R (I'm not very well versed with apply/map/etc., so maybe one of those will work?). Usually I would use mutate to create one column at a time, but I couldn't do that here.

This is my first attempt at posting reprex, so hopefully what I'm trying to do is clear! Can anyone point me in a direction to accomplish this without a loop? Speed definitely matters in the end as well if there are competing ideas.

library(dplyr)

projection_month <- c(seq(0,10,1))
reserve <- c(seq(10000,9000,-100))
surplus <- c(seq(4000,3990,-1))

calc_df <- data.frame(projection_month,reserve, surplus)
calc_df <- cbind(calc_df, assets=0, stat_surplus_total=0, inv_income_on_rsv=0, dividend=0, distributable_earnings=0)

return_rate = .04
counter=2
while(counter < 12){
  calc_df[counter,"inv_income_on_rsv"] = 
    if_else(calc_df[counter,"projection_month"] == 1,
            return_rate/12*calc_df[counter-1,"reserve"],
            calc_df[counter-1,"stat_surplus_total"])*return_rate/12
  calc_df[counter,"distributable_earnings"] = 
            calc_df[counter,"inv_income_on_rsv"]+
            calc_df[counter,"surplus"]-calc_df[counter-1,"surplus"]
  calc_df[counter,"dividend"] =
  if_else(calc_df[counter,"projection_month"]==1,min(calc_df[counter,"distributable_earnings"],0),
            calc_df[counter-1,"stat_surplus_total"]-calc_df[counter-1,"surplus"]+calc_df[counter,"distributable_earnings"])
  calc_df[counter,"assets"] =
    calc_df[counter-1,"assets"] +
    calc_df[counter,"reserve"] - calc_df[counter-1,"reserve"] *
    if_else(calc_df[counter,"projection_month"]==1,0,1) +
    calc_df[counter,"inv_income_on_rsv"] -calc_df[counter,"dividend"]
  calc_df[counter,"stat_surplus_total"] =
      calc_df[counter,"assets"] - calc_df[counter,"reserve"]
    
  
  counter = counter+1
 }

Created on 2022-11-25 with reprex v2.0.2

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.