r - 如何多次运行一个函数并将结果写入列表?

标签 r list matrix replicate

我有一个创建矩阵的函数,我想调用这个函数一千次,这样最后我就有了一个包含 1000 个矩阵的列表。这是一个例子:

set.seed(1)
gen_mat <- function(x) matrix(c(1, 1, 1, x + rnorm(1)), nrow = 2)

现在,我尝试了 replicate(10, gen_mat(1)) ,但这会返回一个数组而不是一个列表。怎么做?

最佳答案

结合上述答案,评论和我自己的答案。当然,我更喜欢我的。另外,我认为上述 base 的答案有误。 R。

n <- 10

# give 1 to gen_mat n-times
lapply(rep(1, n), gen_mat)

# replicate n-times 
replicate(n, gen_mat(1), simplify=FALSE)

# lapply returns error if FUN is not function or 
# the function is not taking an argument. Hence a dummy function.
lapply(seq_len(n), function(x) gen_mat(1))

三种方法的微基准测试

我为 n 使用了更大的值,但在我的桌面上结果相似,n 更小也是。为此,replicate比其他两种方法花费的时间更长。
set.seed(1)
gen_mat <- function(x) matrix(c(1, 1, 1, x + rnorm(1)), nrow = 2)
n <- 1000 

library(microbenchmark)
library(ggplot2)

mb <- microbenchmark(
  lap1 = {lapply(rep(1, n), gen_mat)},
  repl = {replicate(n, gen_mat(1), simplify=FALSE)},
  lap2 = {lapply(seq_len(n), function(x) gen_mat(1))},
  times = 10000L
)

mb
# Unit: milliseconds
# expr      min       lq     mean   median       uq      max neval cld
# lap1 2.839435 3.494157 4.806954 3.854269 5.611413 103.0111 10000  a 
# repl 3.091829 3.777199 5.140789 4.165856 6.013591 101.4318 10000   b
# lap2 3.131491 3.761274 5.089170 4.140316 5.939075 101.1983 10000   b

autoplot(mb)

enter image description here

关于r - 如何多次运行一个函数并将结果写入列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46104176/

相关文章:

java - 矩阵到 JTable

r - 预测 cv.glmnet 为每一行 r 提供相同的值

r - 如何将 openstreetmap 与 R 中的点结合起来

javascript - 当我尝试为我的待办事项列表应用程序创建 LI 元素时,我的浏览器屏幕上没有显示任何内容

函数式语言的列表设计

c - C中删除方阵中的一列和一行

矩阵乘法中的 java.lang.ArrayIndexOutOfBoundsException

c++ - 通过 Rcpp 正确注册插件以使用 Eigen

r - 如何在 Shiny 应用程序中下载 PDF 文件

c# - 合并列表并只返回重复项