我有两个载体
Returns<-c(1.0582529,1.2707149,1.301343,1.1060686,1.0943494)
Contributions <-c(1000,1250,1500,1750,2000)
我希望通过贡献+下一行贡献多次返回贡献
所以
Returns[1] *Contributions [1] = Result 1
Returns [2] * Result 1 + Contributions [2] =Results 2
等
结果将是
Results = c(1058.2529,2933.131353,5769.024454,8316.556852,11289.9178)
答案 0 :(得分:0)
答案出自大卫·阿伦堡。内存预分配和for
循环。
Returns <- c(1.0582529, 1.2707149, 1.301343, 1.1060686, 1.0943494)
Contributions <- c(1000, 1250, 1500, 1750, 2000)
Results <- numeric(length(Returns))
Results[1] <- Returns[1] * Contributions[1]
for (i in seq_along(Results)[-1]) {
Results[i] <- Returns[i] * (Results[i - 1] + Contributions[i])
}
Results
# [1] 1058.253 2933.131 5769.024 8316.557 11289.918