R中的矢量化模拟

vectorized simulation in R

我在R中写了一个模拟函数。我想做 num 模拟。我没有使用 for 循环,而是尝试使用某种应用函数,例如 lapplyparallel::mclapply

lapply,因为我目前正在使用它,所以失败了。

例如:

# t1() is a generic example function
t1 <- function() {data(cars); return(get("cars"))}
a <- t1() # works
a2 <- vector("list", 5) # pre-allocate list for 5 simulations
# otherwise: a2 <- vector("list", num) # where num was pre-specified
a2 <- lapply(a2, t1) 
## Error in FUN(X[[1L]], ...) : unused argument (X[[1]])

我做错了什么?提前致谢!

我宁愿不需要做:

a2 <- vector("list", 5)
for (i in 1:5) {
  a2[[i]] <- t1()
}

a <- t1() 确实有效,但 a <- t1(2) 会 "worked" 是不正确的。您正试图将参数传递给不存在的参数。在参数列表中放置一个虚拟参数,一切都会好起来的。您还可以查看 replicate 函数。它专为支持模拟工作而设计。我想你会发现它不需要在参数列表中包含虚拟参数。

> t1 <- function(z) {data(cars); return(get("cars"))}
> a <- t1() # works
> a2 <- vector("list", 5) # pre-allocate list for 5 simulations
> # otherwise: a2 <- vector("list", num) # where num was pre-specified
> a2 <- lapply(a2, t1) ;str(a2)
List of 5
 $ :'data.frame':   50 obs. of  2 variables:
  ..$ speed: num [1:50] 4 4 7 7 8 9 10 10 10 11 ...
  ..$ dist : num [1:50] 2 10 4 22 16 10 18 26 34 17 ...
 $ :'data.frame':   50 obs. of  2 variables:
  ..$ speed: num [1:50] 4 4 7 7 8 9 10 10 10 11 ...
  ..$ dist : num [1:50] 2 10 4 22 16 10 18 26 34 17 ...
 $ :'data.frame':   50 obs. of  2 variables:
  ..$ speed: num [1:50] 4 4 7 7 8 9 10 10 10 11 ...
  ..$ dist : num [1:50] 2 10 4 22 16 10 18 26 34 17 ...
 $ :'data.frame':   50 obs. of  2 variables:
  ..$ speed: num [1:50] 4 4 7 7 8 9 10 10 10 11 ...
  ..$ dist : num [1:50] 2 10 4 22 16 10 18 26 34 17 ...
 $ :'data.frame':   50 obs. of  2 variables:
  ..$ speed: num [1:50] 4 4 7 7 8 9 10 10 10 11 ...
  ..$ dist : num [1:50] 2 10 4 22 16 10 18 26 34 17 ...
>