R - multiple nested loops

本小妞迷上赌 提交于 2019-11-30 23:01:20

Looping is almost never the best way to accomplish a task in R. It sounds like you want to multiply some initial value by the cumulative product of random numbers, and store this as the columns of a matrix. cumprod is how to get a cumulative product in R:

tmax = 100
initial.row = 1:10
rbind(initial.row, sapply(initial.row,
                          function(x) x*cumprod(exp(rnorm(tmax-1, mean=.02, sd=.1)))))

#                 [,1]       [,2]      [,3]     [,4]      [,5]      [,6]       [,7]       [,8]      [,9]     [,10]
# initial.row 1.000000   2.000000  3.000000 4.000000  5.000000  6.000000   7.000000   8.000000  9.000000 10.000000
#             1.211479   2.483438  3.376012 3.684407  5.611144  5.689530   6.115748   7.809380  8.364223 10.748108
#             1.221254   2.832064  3.500622 3.417095  5.047067  5.706181   6.445985   9.031854  8.125584 10.115107
#             1.350398   3.002284  3.723416 3.581471  5.121880  7.300373   8.008373  10.679728  7.167270 10.310810
#             1.269193   2.883153  3.546245 3.160029  5.312947  7.983395   6.986608  11.226517  7.166026  9.195459
#             ...
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!