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

Joe*_*Joe 5 r list matrix replicate

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

set.seed(1)
gen_mat <- function(x) matrix(c(1, 1, 1, x + rnorm(1)), nrow = 2)
Run Code Online (Sandbox Code Playgroud)

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

Sur*_*ren 6

以上答案,评论和我自己的答案的组合。自然,我更喜欢我的。另外,我认为上述baseR的答案有误。

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))
Run Code Online (Sandbox Code Playgroud)

微基准测试的三种方法

我为设置了较大的值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)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明