用利率向量计算复利 [英] Calculating compound interest with vector of rates
问题描述
我正在尝试查看是否有一种方法可以对我执行的计算进行向量化.我搜索了这个答案,却找不到我需要的东西.
I'm trying to see if there is a way to vectorize a calculation I performed. I searched for this answer and couldn't find what I needed.
我有一个增长速度的向量.每个代表一个时期(在我的情况下为一年).我想将此向量应用于一些本金.然后,在将第一个增长率应用于主体后,使用第一次迭代的结果,并将第二个增长元素应用于新值.
I have a vector of growth rates. Each one represents one period (one year in my case). I want to apply this vector to some principal amount. Then, after the first growth rate is applied to the principal, use the result from the first iteration and apply the second growth element to the new value.
这里有一些要复制的代码(全部在base
中):
Here's some code for reproduction (all in base
):
# Vector of interest or inflation rates
RateVector <- c(0.02, 0.03, 0.04, 0.05, 0.06, 0.05, 0.04, 0.03, 0.02, 0.01) # forecasted rates
Principal <- data.frame(Principal = 1000000) # actual value of indicator in most recent period as data frame (list)
这是我进行矢量化的尝试:
Here was my attempt to vectorize:
sapply(Principal, "*", 1 + cumsum(RateVector))
此问题是sapply
函数不会保存新金额,而是将费率向量应用于相同的初始本金.这实际上是我从这段代码中所期望的.我不知道如何在每次迭代之间保存新的值.
The problem with this is that the sapply
function does not save the new amount and instead applies the vector of rates to the same initial principal. This is actually what I expected from this code. I don't know how to go about saving the new value after each iteration from element to element.
这是我使用循环解决问题的方法:
This is how I solved the problem, using a loop:
AmountVector <- Principal # initialize output vector
# Compound growth growth calculation loop
for(i in 1:length(RateVector)){
Principal = Principal * (1 + RateVector)[i]
AmountVector <- rbind(AmountVector,Principal)
}
# Print result
AmountVector
推荐答案
这是累积产品",因此?cumprod
是您所需要的:
This is a "cumulative product", so ?cumprod
is what you need:
1000000 * cumprod(1+RateVector)
# [1] 1020000 1050600 1092624 1147255 1216091 1276895 1327971 1367810 1395166
#[10] 1409118
cbind(AmountVector, newresult = 1000000 * c(1,cumprod(1+RateVector)))
# Principal newresult
#1 1000000 1000000
#2 1020000 1020000
#3 1050600 1050600
#4 1092624 1092624
#5 1147255 1147255
#6 1216091 1216091
#7 1276895 1276895
#8 1327971 1327971
#9 1367810 1367810
#10 1395166 1395166
#11 1409118 1409118
这篇关于用利率向量计算复利的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!