我有一组模拟增长率,比如 8 个时间段(和 5 个模拟增长路径),
r <- matrix(rnorm(40,0.05,0.01),5,8)
r
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 0.04229559 0.02846659 0.04948458 0.06144443 0.05657848 0.05782358 0.05545835 0.04090866
[2,] 0.06270360 0.06045967 0.04213729 0.05413941 0.06291148 0.05382643 0.05844549 0.03824342
[3,] 0.07846056 0.05503713 0.06800700 0.05888937 0.05759237 0.03789024 0.05250413 0.05011601
[4,] 0.04248757 0.04632404 0.04199074 0.04542522 0.03473972 0.04129197 0.06614095 0.06024244
[5,] 0.04382759 0.03555406 0.06630673 0.06019894 0.05057905 0.06336362 0.04954486 0.05092946
然后,我想使用这些费率进行投影x_{t+1} = x_{t} (1+r_{t})
。我可以使用for
循环来做到这一点,
x.fn<-function(x,rr){
xx<-cbind(x,rr)
for(i in 1:ncol(rr)){
xx[,i+1]<-xx[,i]*(1+rr[,i])
}
xx
}
x.fn(x=100, rr=r)
x
[1,] 100 104.4835 110.8389 116.7353 122.0573 128.6441 136.0210 142.7797 146.9829
[2,] 100 106.1199 111.8381 115.9955 120.3976 125.9980 132.5384 138.1477 142.3214
[3,] 100 103.5990 106.6866 111.5629 117.5999 124.9613 131.6552 137.2966 142.9163
[4,] 100 105.7215 109.7624 113.8707 120.5216 128.8663 136.1915 143.3542 150.7466
[5,] 100 104.1080 109.6981 112.7072 118.6346 126.1118 130.1564 135.8039 142.0652
是否可以加快速度/避免使用for
带有apply
类型函数的循环?