gpt4 book ai didi

r - parLapply - 如何解决错误 "Could not find function "bindToEnv""?

转载 作者:行者123 更新时间:2023-12-04 00:59:28 24 4
gpt4 key购买 nike

我想使用 parLapply 并且我正在设置我的代码,就像这里介绍的那样:http://www.win-vector.com/blog/2016/01/parallel-computing-in-r/

最后几次效果很好。但是,以我目前的 parLapply调用我收到错误Error in checkForRemoteErrors(val) : 3 nodes produced errors; first error: could not find function "bindToEnv" .

这里有一个简短的例子:

#' Copy arguments into env and re-bind any function's lexical scope to bindTargetEnv .
#'
#' See http://winvector.github.io/Parallel/PExample.html for example use.
#'
#'
#' Used to send data along with a function in situations such as parallel execution
#' (when the global environment would not be available). Typically called within
#' a function that constructs the worker function to pass to the parallel processes
#' (so we have a nice lexical closure to work with).
#'
#' @param bindTargetEnv environment to bind to
#' @param objNames additional names to lookup in parent environment and bind
#' @param names of functions to NOT rebind the lexical environments of
bindToEnv <- function(bindTargetEnv=parent.frame(),objNames,doNotRebind=c()) {
# Bind the values into environment
# and switch any functions to this environment!
for(var in objNames) {
val <- get(var,envir=parent.frame())
if(is.function(val) && (!(var %in% doNotRebind))) {
# replace function's lexical environment with our target (DANGEROUS)
environment(val) <- bindTargetEnv
}
# assign object to target environment, only after any possible alteration
assign(var,val,envir=bindTargetEnv)
}
}

ccc <- 1

# Parallel
cl <- parallel::makeCluster(getOption("cl.cores", 3))
junk <- parallel::clusterEvalQ(cl, c(library(data.table)))

f <- function(x) {
bindToEnv(objNames = 'ccc')

return(x+x)
}

b <- do.call(rbind, parallel::parLapply(cl, 1:10, f))

如果我不添加 bindToEnv一切正常。我究竟做错了什么?谢谢!

最佳答案

您需要使用 clusterExport()在创建集群之前导出您定义的使用过的函数和对象。

library(parallel)
cl <- makeCluster(getOption("cl.cores", 3))
clusterEvalQ(cl, c(library(data.table)))
clusterExport(cl, c("bindToEnv", "ccc"),
envir=environment())
f <- function(x) {
bindToEnv(objNames='ccc')
return(x+x)
}

b <- do.call(rbind, parallel::parLapply(cl, 1:10, f))
b
# ,1]
# [1,] 2
# [2,] 4
# [3,] 6
# [4,] 8
# [5,] 10
# [6,] 12
# [7,] 14
# [8,] 16
# [9,] 18
# [10,] 20

stopCluster(cl)

关于r - parLapply - 如何解决错误 "Could not find function "bindToEnv""?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59744462/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com