我是这个论坛和 R 的新手,所以如果我的问题不清楚或者我不遵循这个论坛的“不成文规则”,我事先表示歉意。
我正在 R 中使用 for 循环进行模拟研究,该循环运行一个函数多次。我想在每次 for 循环运行函数时将函数的结果写入列表中。我想将这些列表与 dim(x,x,模拟次数) 合并在一个数组中。 我不确定这是否是正确的方法,基本上我正在寻找一种方法来存储我的 X(模拟数量)列表,并以方便的方式将结果存储在一个变量中(因此我可以将此变量用作 VAR[ i] <- 函数.. 在我的 for 循环中)。
我希望我的意思很清楚。我认为我的示例代码更清楚地说明了我正在寻找的内容:
非常感谢各种提示/建议/答案!
#These are e.g. the variables I get as output from the function.
a <- matrix(NA, 2,1)
b <- matrix(NA,2,1)
beta <- matrix(NA,2,1)
bp <- array(NA,c(2,2,2))
#I save these variables in a list (this is done already in the function self)
results <- list(a = a, b = b, beta = beta, bp = bp)
#Now, I would like to create an array to save this list each time I run the
#function in my for loop. I tried this, but did not succeed:
results2 <- array(results, c(1,1,10))
results3 <- array(rep(results))
最佳答案
如果我正确理解你的问题,你可能只想使用另一个列表
存储函数 fun
的所有输出(作为示例,我使函数的返回值依赖于函数参数 x
)
fun <- function(x){
##These are e.g. the variables I get as output from the function.
a <- matrix(x/2, 2,1)
b <- matrix(x/2,2,1)
beta <- matrix(x/2,2,1)
bp <- array(x/2,c(2,2,2))
list(a = a, b = b, beta = beta, bp = bp)
}
然后您可以使用 lapply
它是 for 循环的包装器,以便获取包含所有结果的列表(此处该函数被调用 100 次):
all.results <- lapply(1:100, fun)
您现在可以使用 all.results[[1]]
、all.results[[2]]
等访问每个函数调用的结果。
或者,如果您想使用 for
循环:
all.results <- list()
for (i in 1:100){
all.results[[i]] <- fun(i)
}
这有帮助吗?
关于arrays - 在 R 中的数组中复制列表的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16445716/