[英]vectorized simulation in R
I've written a simulation function in R . 我已经在R中编写了一个仿真函数。 I'd like to do num
simulations. 我想进行num
模拟。 Rather than using a for loop, I'm trying to use some sort of apply function, such as lapply
or parallel::mclapply
. 我尝试使用某种应用功能,而不是使用for循环,例如lapply
或parallel::mclapply
。
lapply
, as I'm currently using it, is failing. 我目前正在使用的lapply
失败了。
For example: 例如:
# 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]])
What am I doing wrong? 我究竟做错了什么? Thanks in advance! 提前致谢!
I'd rather not need to do: 我宁愿不需要做:
a2 <- vector("list", 5)
for (i in 1:5) {
a2[[i]] <- t1()
}
It's true that a <- t1()
works but it's not true that a <- t1(2)
would have "worked". 这是真的, a <- t1()
的作品,但它不是真的, a <- t1(2)
将有“工作”。 You are trying to pass arguments to parameters that are not there. 您正在尝试将参数传递给不存在的参数。 Put a dummy parameter in the argument list and all will be fine. 将一个虚拟参数放在参数列表中,一切都会好的。 You might also look at the replicate
function. 您可能还会查看replicate
功能。 It is specifically designed to support simulation efforts. 它是专门为支持仿真工作而设计的。 I think you will find that it does not require including dummy parameters in the argument list. 我认为您会发现它不需要在参数列表中包含虚拟参数。
> 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.