簡體   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