带有并行包和foreach包“任务1失败-”找不到”错误的排列错误

问题描述 投票:0回答:1

我不确定如何解决此问题。我尝试在此处.packages="foreach"中添加Function not found in R doParallel 'foreach' - Error in { : task 1 failed - "could not find function "raster"",但无法使其正常工作。非常感谢您的帮助!

####################
install.packages("doParallel")
install.packages("doSNOW")
install.packages("doParallel") 
install.packages("doMPI")
install.packages("tidyverse")

# Load packages -----------------------------------------------------------
rm(list = ls())
library(tidyverse)
library(foreach)
library(doSNOW)
library(doMPI)
library(doParallel)
registerDoParallel()

# Single iteration function -------------------------------------------------------------
one_iteration <- function(snps, estuaries) {
  sim_snps <- matrix(data = NA, nrow = snps, ncol = estuaries) %>% 
    as.data.frame(.)
  for (i in 1:snps) {
    sim_snps[i, ] <- sample(x = c(0,0,0, 1,1,1), size = estuaries, replace = F)
  }
  nbig <- rowSums(sim_snps)

  c(sum(nbig == 3), sum(nbig == 2), sum(nbig == 1), sum(nbig == 0))
}

# Permutations function ---------------------------------------------------
doNullPermutations <- function(nit, snps, estuaries) {
  start <- summary(proc.time())[3] # get time at start of function
  x <- foreach(iteration = 1:nit, # do 100 iterations
               .combine = rbind) %dopar% one_iteration(snps, estuaries)
  print(summary(proc.time())[3] - start) # print time elapse (time at end minus the start)
  return(x)
}

# 3 estuaries -------------------------------------------------------------
perms_res_3est_10kperm <- doNullPermutations(1, snps = 20083, estuaries = 3)
**Error in one_iteration(snps, estuaries) : 
  task 1 failed - "could not find function "one_iteration""
Called from: e$fun(obj, substitute(ex), parent.frame(), e$data)**
r permutation
1个回答
2
投票

下面的代码应该起作用。出现此错误的原因是,foreach函数会在新会话中创建新工作线程,而在这些会话中,不会导出主会话中的函数和包。因此,请注意.export参数和.packages参数。

# Permutations function ---------------------------------------------------
doNullPermutations <- function(nit, snps, estuaries) {
    x <- foreach(iteration = 1:3, # do 100 iterations
               .combine = rbind,
               .export = ls(globalenv()),
               .packages = 'tidyverse') %dopar% one_iteration(snps, estuaries)
    return(x)
}

perms_res_3est_10kperm <- doNullPermutations(1, snps = 20083, estuaries = 3)
© www.soinside.com 2019 - 2024. All rights reserved.