我正在尝试编写一个嵌套循环代码来模拟具有 101 行的数据框中的 10 列数据。第一行数据已被指定为起始值。每列应该不同,因为我的矩阵 r 是从随机法线生成的;但是,每列中的结果值完全相同。为循环索引提供一些上下文:
tmax=100; ncol(pop_sims) = 12 (so a total of 10 iterations, 3-12); ncol(r) = 10
for (i in 1:tmax){
for (j in 3:ncol(pop_sims)){
for(k in 1:ncol(r)){
if (pop_sims[i,j]*exp(r[i,k]) <2) {
pop_sims[i+1,j]<- 0}
else {
pop_sims[i+1,j] <- pop_sims[i,j]*exp(r[i,k])}
}}}
Run Code Online (Sandbox Code Playgroud)
任何想法将不胜感激。
更新:我没有使用多个循环,而是省略了矩阵 r 的使用并简化了我的循环。
for (i in 1:tmax){
for (j in 1:10){
if (pop_sims[i,j]*exp(r[i,j]) <2) {
pop_sims[i+1,j]<- 0}
else {
pop_sims[i+1,j] <- pop_sims[i,j]*exp(rnorm(1,mean=0.02, sd=0.1))}
}}
Run Code Online (Sandbox Code Playgroud)
循环几乎从来都不是在 R 中完成任务的最佳方式。听起来您想要将某个初始值乘以随机数的累积乘积,并将其存储为矩阵的列。cumprod是如何在 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
# ...
Run Code Online (Sandbox Code Playgroud)