简体   繁体   中英

vectorized simulation in R

I've written a simulation function in R . I'd like to do num simulations. Rather than using a for loop, I'm trying to use some sort of apply function, such as lapply or parallel::mclapply .

lapply , as I'm currently using it, is failing.

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". 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. 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 ...
> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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