如何多次运行一个函数并将结果写入列表? [英] How to run a function multiple times and write the results to a list?
问题描述
我有一个创建矩阵的函数,因此我想调用此函数一千次,最终得到1000个矩阵的列表.这是一个示例:
I have a function that creates a matrix and I want to call this function a thousand times such that in the end I have a list of 1000 matrices. Here is an example:
set.seed(1)
gen_mat <- function(x) matrix(c(1, 1, 1, x + rnorm(1)), nrow = 2)
现在,我尝试了replicate(10, gen_mat(1))
,但这将返回一个数组而不是一个列表.怎么做?
Now, I tried replicate(10, gen_mat(1))
, but this returns an array and not a list. How to do it?
推荐答案
上述答案,评论和我自己的答案的组合.自然,我更喜欢我的.另外,我认为上述base
R的答案有误.
Combination of above answer, comment, and my own answer. Naturally, I like mine better. Also, I think there is a mistake in the above answer for 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
比其他两种方法花费的时间更长.
I used a larger value for n
, but the results are similar in my desktop with smaller n
as well. For this, replicate
takes longer than the other two methods.
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)
这篇关于如何多次运行一个函数并将结果写入列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!