在R中的数组中复制列表的元素

时间:2013-05-08 16:32:34

标签: arrays r list

我是这个论坛和R的新手,所以如果我的问题不清楚或者我没有完成本论坛的“不成文规则”,我事先道歉。

我正在使用for循环进行模拟研究,该循环运行多次函数。每次for循环运行函数时,我想在列表中写入函数的结果。我希望将这些列表组合在一个数组中,使用dim(x,x,模拟次数)。 我不确定这是否是正确的方法,基本上我正在寻找一种方法来存储我的X(模拟的数量) - 在一个变量中以便利的方式结果列表(所以我可以将此变量用作VAR [我]< - 函数..在我的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))

1 个答案:

答案 0 :(得分:2)

如果我正确理解您的问题,您可能只想使用其他列表 存储函数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)
}

这有帮助吗?