繁体   English   中英

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)将有“工作”。 您正在尝试将参数传递给不存在的参数。 将一个虚拟参数放在参数列表中,一切都会好的。 您可能还会查看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 ...
> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM