繁体   English   中英

我可以并行化默认返回列表的 function 吗? (在 R 中)

[英]Can I parallelize a function which by default returns a list? (in R)

我可以并行化默认返回列表的 function 吗? (在 R 中)我尝试使用并行 package 的 parLapply function,但我没有成功。

是的, parLapply可以返回列表列表。 如果 parLapply 调用的parLapply返回一个列表,这就是你得到的。

library(parallel)

# data 
data(mtcars)

# function - model fit on bootstrapped samples from the Boston dataset
model_fit <- function(x) {
  n <- nrow(mtcars)
  i <- sample(n, n, replace = TRUE)
  fit <- lm(mpg ~ ., data = mtcars[i, ])
  fit
}

# detect the number of cores
n.cores <- detectCores() - 2L
# Repl bootstrap replicates
Repl <- 100L

cl <- makeCluster(n.cores)
clusterExport(cl, "mtcars")
model_list <- parLapply(cl, 1:Repl, model_fit)
stopCluster(cl)

# a list of class "lm"
summary(model_list[[1]])
#> 
#> Call:
#> lm(formula = mpg ~ ., data = mtcars[i, ])
#> 
#> Residuals:
#>      Min       1Q   Median       3Q      Max 
#> -2.86272 -0.80106 -0.08815  0.68233  2.79325 
#> 
#> Coefficients:
#>               Estimate Std. Error t value Pr(>|t|)    
#> (Intercept) -19.353679  20.403857  -0.949 0.353648    
#> cyl          -9.469350   1.921317  -4.929 7.10e-05 ***
#> disp          0.008405   0.014370   0.585 0.564876    
#> hp            0.037101   0.020395   1.819 0.083185 .  
#> drat          9.573765   2.289820   4.181 0.000421 ***
#> wt           -2.543876   2.111203  -1.205 0.241630    
#> qsec          3.360474   1.091440   3.079 0.005692 ** 
#> vs          -32.223824   6.698522  -4.811 9.39e-05 ***
#> am          -26.326478   5.534103  -4.757 0.000107 ***
#> gear         11.903213   2.420963   4.917 7.30e-05 ***
#> carb         -4.022473   1.047176  -3.841 0.000949 ***
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#> 
#> Residual standard error: 1.745 on 21 degrees of freedom
#> Multiple R-squared:  0.9437, Adjusted R-squared:  0.9169 
#> F-statistic:  35.2 on 10 and 21 DF,  p-value: 7.204e-11

代表 package (v2.0.1) 于 2022 年 9 月 2 日创建

暂无
暂无

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

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