如何使此代码并行运行?对于循环

问题描述

我正在尝试将此简单的for循环作为并行过程运行,因为它需要大量的计算能力。有什么想法吗?

##Load files and libraries---
library(tidyverse)
library(caret)
library(insight)
library(MASS)
library(mfx)
library(furrr)

for (i in 1:16) {
      nested_inter$model[[i]]<- nb_thesis_inter(df= nested_nb$data[[i]],mdl= nested_nb$model[[i]])
      print (paste("Finished model ",i,"out of 16"))
    }

  #nested_inter<- nested_inter %>% 
  #  mutate(model= future_map2(.x= data,.y=model,.f = nb_thesis_inter))

解决方法

我要去的是future.apply包裹。

library(future.apply)
plan(multisession)

nested_inter$model = future_Map(nb_thesis_inter,nested_nb$data,nested_nb$model)

需要注意的两件事。

  1. plan(multisession)允许Windows并行使用。有关所有选项,请参见?plan
  2. 我没有安装所有软件包,因为该示例不可复制。根据默认参数顺序future_Map,可能需要将future_map(function (x,y) nb_thesis_inter(df = x,mdl = y),...)调用更改为nb_thesis_inter
,

您可以使用pmap

nested_nb %>% furrr::future_pmap(function(...){
  row <- list(...)
  nb_thesis_inter(df = row$data,mdl= row$model)
})