【问题标题】:R, error 'could not find function' in foreach with timeOutR,foreach 中的错误“找不到函数”,timeOut
【发布时间】:2018-02-07 09:02:17
【问题描述】:

我想在foreach 中插入一个这样的超时控制:

#Parallel function
runnable_X<-function(ID) {
  require(R.utils)
  Sys.sleep(ID)
  return(ID)
}

#foreach function with timeout
foreach_timeOut<-function() {
  tryCatch({
    require(R.utils)
    withTimeout({

      out_list<-foreach(ID=c(1:20),.options.multicore=list(preschedule=FALSE)) %dopar% runnable_X(ID)

    },
    timeout=5); ### Cumulative Timeout for entire process
  }, TimeoutException=function(ex) {
    return("Time Out!")
  })
} 


library(doParallel)
require(R.utils)

#Parallel registration
registerDoParallel()

#NUmber of cores
options(cores=5)

foreach_timeOut()

我有这个错误:

Error in runnable_X(ID) : 
  task 1 failed - "could not find function "runnable_X""

如果我在 foreach_timeout 中声明 runnable_X 函数,这不会发生,但我不能这样做。

【问题讨论】:

    标签: r function foreach timeout


    【解决方案1】:

    如果使用内置函数,则必须将它们添加到集群中:

    N_CORES <- 5   
    cl <- makeCluster(N_CORES, outfile = "")
    registerDoParallel(cl)
    clusterEvalQ( cl, {
    
      runnable_X <- function() { stuff }
    
    })
    

    【讨论】:

    • 我使用的是registerDoParallel自动创建的集群,我没有使用makeCluster
    • 我明白了,尽管您可以通过添加行来创建集群来解决您的问题,并且它不会对代码产生任何影响
    • 这只是一个“玩具代码”,出于其他原因,我不想创建集群。如果我在一个临时包中有这个函数,这个函数将在 foreach 中可见?
    • 如果这个函数是洞察一个包,你应该输入:foreach(x, .packages = c("package_adhoc")) %dopar%
    【解决方案2】:

    感谢@karen 的帮助 (+1),以防我们有集群,但我发现这个解决方案更适合我的情况。

    #Parallel function
    runnable_X<-function(ID) {
      require(R.utils)
      Sys.sleep(ID)
      return(ID)
    }
    

    我将在我的函数中添加 foreach export 命令

    #foreach function with timeout
    foreach_timeOut<-function() {
      tryCatch({
        require(R.utils)
        withTimeout({
    
          out_list<-foreach(ID=c(1:20),
                            .options.multicore=list(preschedule=FALSE),
                            .export = c("runnable_X")
                            ) %dopar% runnable_X(ID)
    
        },
        timeout=5); ### Cumulative Timeout for entire process
      }, TimeoutException=function(ex) {
        return("Time Out!")
      })
    } 
    
    
    library(doParallel)
    require(R.utils)
    
    #Parallel registration
    registerDoParallel()
    
    #NUmber of cores
    options(cores=5)
    
    foreach_timeOut()
    [1] "Time Out!"
    

    其他topic相关。

    【讨论】:

      猜你喜欢
      • 2016-08-02
      • 1970-01-01
      • 2020-03-15
      相关资源
      最近更新 更多