首页 > 解决方案 > 使用带有检查点的 foreach 时未找到 R 包的内部函数

问题描述

这是这个问题的后续问题:How to set .libPaths (checkpoint) on workers when running parallel computing in R

根据答案,我将以下代码(简化示例)放入名为“test1”的 R 包中:

#' @export
f <- function() {
  `%dopar%` <- foreach::`%dopar%`
  doFuture::registerDoFuture()
  libs <- .libPaths()

  res <- foreach::foreach(x = 1:2) %dopar% {

    cat(sprintf("Initial Library paths used by worker (PID %d):\n", Sys.getpid()))
    cat(sprintf(" - %s\n", sQuote(.libPaths()[1])))

    ## Use the same library paths as the master R session
    .libPaths(libs)

    cat(sprintf("Library paths used by worker (PID %d):\n", Sys.getpid()))
    cat(sprintf(" - %s\n", sQuote(.libPaths()[1])))

    x + g()
  }

  res
}


g <- function() {
  h()
}

h <- function() {
  runif(1)
}

然后我调用checkpoint::checkpoint("2018-07-24")并将包安装到检查点库中。然后下面的代码产生了这个错误:

checkpoint::checkpoint("2018-07-24")
future::plan("multisession")
test1::f()

工作人员使用的初始库路径(PID 16880):-'C:/Programme/R-3.5.1/library'

工作人员使用的库路径(PID 16880):-'.../.checkpoint/2018-07-24/lib/x86_64-w64-mingw32/3.5.1'

工作人员使用的初始库路径(PID 3916):-'C:/Programme/R-3.5.1/library'

工作人员使用的库路径(PID 3916):-'.../.checkpoint/2018-07-24/lib/x86_64-w64-mingw32/3.5.1'

{ 中的错误:任务 1 失败 - “找不到函数“h””

test1:::g()当我在通话中明确调用foreach时,它可以工作。有人可以解释一下,为什么我必须在 foreach 循环中显式调用我自己的包的函数:::?看起来g()好像找到了,但h()后来没有?

标签: rr-future

解决方案


推荐阅读