作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试查看是否有办法对我执行的计算进行矢量化。我搜索了这个答案,但找不到我需要的东西。
我有一个增长率向量。每一个代表一个时期(在我的例子中是一年)。我想将此向量应用于一些本金。然后,在将第一个增长率应用于主体后,使用第一次迭代的结果并将第二个增长元素应用于新值。
这里有一些复制代码(全部在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)
这是我对矢量化的尝试:
sapply(Principal, "*", 1 + cumsum(RateVector))
问题在于 sapply
函数不会保存新的金额,而是将利率向量应用于相同的初始本金。这实际上是我对这段代码的期望。我不知道如何在每次迭代后从一个元素到另一个元素保存新值。
这就是我使用循环解决问题的方法:
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
是你需要的:
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
关于r - 用利率向量计算复利,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50593439/
我需要 Euribor 利率来计算网站上的抵押贷款利率。有谁知道是否有提供此数据的服务,可能是 XML 格式?RSS 提要可以,免费或付费。谢谢! 最佳答案 有这样的服务的商业供应商: http://
我是一名优秀的程序员,十分优秀!