【问题标题】:Replicate elements of a list in an array in R在R中的数组中复制列表的元素
【发布时间】:2013-05-08 16:32:33
【问题描述】:

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

我正在 R 中使用 for 循环进行模拟研究,该循环多次运行一个函数。我想将函数的结果写在一个列表中,每次 for 循环运行该函数时。我想将这些列表与 dim(x,x,Number of simulations) 组合成一个数组。 我不确定这是否是正确的方法,基本上我正在寻找一种方法将我的 X(模拟次数)列表与结果以一种方便的方式存储在一个变量中(所以我可以将此变量用作 VAR[ i]

我希望我的意思很清楚。我认为我的示例代码更清楚地说明了我在寻找什么:

非常感谢各种提示/建议/答案!

#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))

【问题讨论】:

标签: arrays r list


【解决方案1】:

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

这有帮助吗?

【讨论】:

  • 感谢您的快速回答!这确实是我想要的。但是,我需要使用一个 foror 循环,因为我必须在同一个循环中对相同的数据执行其他操作..
  • 谢谢!这确实是我一直在寻找的......而且我无法弄清楚我必须为列表使用哪些维度,尽管解决方案非常明显(就像你所做的那样,只需将列表留空......)有时最明显的是我猜是最难看到的……谢谢!
猜你喜欢
  • 2021-05-17
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-07
  • 1970-01-01
相关资源
最近更新 更多