源 r 代码,为每个 运行 附加特定值。或者有效地通过 lapply 或 for 循环

source r code, append specific value for each run. Or efficifiently pass through lapply or for loop

我正在尝试通过对对象 A 重新采样来有效地 bootstrap 生成的 allYears 输出,对象 A 是 for 循环的每个 运行 之后的矩阵列表,并附加每个 运行 a列表。不幸的是,示例函数是随机绘制的,我想做的就是在每个新循环 运行 之前按顺序重新 运行 object A 并将结果附加到列表中。复制不会重新 运行 对象 A。提前致谢。请参阅下面的代码:

A <- lapply(1:4, function(x)  # construct list of matrices
  matrix(c(0, 0, 10,
           rbeta(1,5,4), 0, 0,
           0, rbeta(1,10,2), 0), nrow = 3,ncol=3, byrow = TRUE, ))

n <- c(1000,100,10)  # initial vector of abundances

nYears = 4  # define the number of years to project over

allYears <- matrix(0,nrow=3,ncol=nYears+1)  # build a storage array for all abundances

allYears[,1] <- n  # set the year 0 abundance   

i1 <- 2:ncol(allYears)

for(t in seq_along(i1)) {
  allYears[,i1[t]] <-  A[[t]] %*% allYears[,i1[t]-1]
}

如果你想在每次迭代前对A创建中的一些参数进行重新采样和更改,我建议如下:

get_A <- function(parameter1){

  a <- lapply(1:4, function(x)  # construct list of matrices
    matrix(c(0, 0, paramter1,   # here I replace 10 with paramter10
           rbeta(1,5,4), 0, 0,
           0, rbeta(1,10,2), 0), nrow = 3,ncol=3, byrow = TRUE, ))

  return(a)

}

n <- c(1000,100,10)  # initial vector of abundances

nYears = 4  # define the number of years to project over

allYears <- matrix(0,nrow=3,ncol=nYears+1)  # build a storage array for all abundances

allYears[,1] <- n  # set the year 0 abundance   

i1 <- 2:ncol(allYears)

for(t in seq_along(i1)) {
  A <- get_A(10*t)
  allYears[,i1[t]] <-  A[[t]] %*% allYears[,i1[t]-1]
}

这里我封装了一个函数并复制。

library(plyr)
set.seed(123)
Stoch_Proj_Function <- function() {A <- lapply(1:4, function(x)  # construct list of matrices
  matrix(c(0, 0, 10,
           rbeta(1,5,4), 0, 0,
           0, rbeta(1,10,2), 0), nrow = 3,ncol=3, byrow = TRUE, ))

n <- c(1000,100,10)  # initial vector of abundances

nYears = 4  # define the number of years to project over

allYears <- matrix(0,nrow=3,ncol=nYears+1)  # build a storage array for all abundances

allYears[,1] <- n  # set the year 0 abundance   

i1 <- 2:ncol(allYears)

for(t in seq_along(i1)) {
  allYears[,i1[t]] <-  A[[t]] %*% allYears[,i1[t]-1]
}

final <- allYears
}

master_array <- replicate(10,Stoch_Proj_Function())
master_list <- alply(master_array,3)