我应该使用 sapply to 运行 不需要参数的模拟吗?

Should I use sapply to run simulations that don't require an argument?

我正在 运行 进行数千次不需要任何参数的模拟。这是一个非常简单的例子:

simulate <- function() sum(sample(1:10, size = 5))

我可以 运行

results <- rep(0,1000)
for(i in 1:1000){
  results[i] <- simulate()
}

...但我读过很多次,for 循环在 R 中很慢,我需要最大化速度(我正在做的实际模拟比这更耗时)。

  1. 我应该在 results 上使用 apply 家族的成员吗?如果是的话怎么办?
  2. 如果 results 的元素不是,sapply 是否仍比 for 循环快 正在模拟功能中使用?

您可以为此使用 sapply,但通常对于这种情况我更喜欢 replicate

set.seed(123)
replicate(10, simulate())
#[1] 29 24 27 29 29 19 22 31 28 23

您还可以在 purrr 中使用 rerun,其行为方式与 replicate 相同。


使用sapply 方式是使用匿名函数。

sapply(1:10, function(X) simulate())