使用R中的Apply Function替代Loop

时间:2017-10-13 12:09:41

标签: r loops apply

寻求帮助。我希望创建一个余额构建,其中每行的起始余额取决于前一行的最终余额。前一行中的结束余额是一个计算:

期末余额=期初余额+付款 - 支出 - (开始余额*会员间)

实际上,计算取决于众多变量,但原则上我要做的是相同的。我希望能够保留前一行的最终余额。我已成功设法使用循环执行此操作,但它非常慢,我想了解在尝试复制相同的输出但使用apply函数时我做错了什么。任何帮助都会很棒。

另外我是Stack Overflow的新手,所以如果我没有以正确的格式发布,那么如果你能让我知道我应该采取哪些不同的做法会很棒。

ToB           <- c(0:5)
Spend         <- c(0,1000,50,50,50,50)
Payment       <- c(0,0,100,150,150,150)
Interest      <- c(0.03,0.03,0.03,0.03,0,0.05) 
End_Balance <- c(0,0,0,0,0,0)
Start_Balance <- rep(0, length(ToB))
Interest_Calc <- rep(0,6)
row <- 0

# initialise End Balance and Start balance
df               <- data.frame(ToB, Spend, Payment, Interest, Interest_Calc, Start_Balance, End_Balance)    

#EXISTING SOLUTION
# populate the remaining balances
for(i in 2:nrow(df)){

  df$Start_Balance[i] <- df$End_Balance[i - 1]
  df$Interest_Calc[i] <- df$End_Balance[i - 1] *Interest[i]
  df$End_Balance[i]   <- df$Start_Balance[i] + df$Payment[i] - df$Spend[i] + df$End_Balance[i - 1] *Interest[i]
  }


#ATTEMPT AT NEW SOLUTION USING APPLY
temp4 <- sapply(2:nrow(df), function (i) {

  df$Start_Balance[i] <- df$End_Balance[i - 1]
  df$Interest_Calc[i] <- df$End_Balance[i - 1] *Interest[i]
  df$End_Balance[i]   <- df$Start_Balance[i] + df$Payment[i] - df$Spend[i] + df$End_Balance[i - 1] *Interest[i]
})

0 个答案:

没有答案