我正在尝试编写一个脚本来获取具有以下约束的存款帐户的余额:
这是我迄今为止的解决方案:
library(tidyverse)
initial_investment <- 22950
rate <- 0.015
overview_invests <- data.frame(id = 1:25, planned_investments = c(rep(1000, 20), rep(0,5))) %>%
rowwise() %>% mutate("balance" = initial_investment * (1 + rate)^id + sum(cumsum(planned_investments) * (1 + rate)^(id:1))) %>% ungroup()
它工作得相当好,但它无法处理planned_investments为零的情况。事实上,在这种情况下,余额会显着下降(我假设我只从初始投资中获得部分总和)。解决起来可能很简单,但我尝试了多种方法但没有成功。
提前感谢您的潜在建议,
对于处理复利问题,使用循环执行此计算会更容易。
planned_investments = c(rep(1000, 20), rep(0,5))
overview_invests<- initial_investment
for( i in 1:25) {
overview_invests<- (overview_invests + planned_investments[i])*(1 + rate)^(1)
print(overview_invests)
}