在foreach循环内找不到函数 [英] could not find function inside foreach loop

查看:574
本文介绍了在foreach循环内找不到函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 一个< -function(... 

我试图用foreach在R中进行多核计算。 。){
foreach(i = 1:10)%dopar%{
B()
}
}

然后我在控制台中调用函数 A 。问题是我正在调用另一个脚本文件中定义的函数 Posdef B 中。我必须把 Posdef 放在 foreach 的输出参数列表中: .export = c ( Posdef)。但是我得到以下错误:

pre $ 错误{:任务3失败 - 无法找到函数Posdef

为什么不能找到这个定义好的函数?

解决方案

简单的回答是,这是一个并行后端的错误,如 doSNOW doParallel doMPI ,但是它已经被修复了。

稍微长一点的答案是 foreach 使用特殊的导出环境将功能导出到工作人员,而不是全局环境。过去,这会导致在全球环境中创建的函数出现问题,因为导出环境不在其范围内,尽管它们现在在相同的导出环境中定义。因此,他们看不到在export环境中定义的任何其他函数或变量,例如Posdef。



doSNOW doParallel doMPI 后台现在将关联环境从全局更改为通过.export导出的函数的导出环境,似乎已经解决了这些问题。

I'm trying to use foreach to do multicore computing in R.

A <-function(....) {
    foreach(i=1:10) %dopar% {
    B()
    }
}

then I call function A in the console. The problem is I'm calling a function Posdef inside B that is defined in another script file which I source. I had to put Posdef in the list of export argument of foreach: .export=c("Posdef"). However I get the following error:

Error in { : task 3 failed - "could not find function "Posdef""

Why cant R find this defined function?

解决方案

The short answer is that this was a bug in parallel backends such as doSNOW, doParallel and doMPI, but it has since been fixed.

The slightly longer answer is that foreach exports functions to the workers using a special "export" environment, not the global environment. That used to cause problems for functions that were created in the global environment, because the "export" environment wasn't in their scope, even though they were now defined in that same "export" environment. Thus, they couldn't see any other functions or variables defined in the "export" environment, such as "Posdef" in your case.

The doSNOW, doParallel and doMPI backends now change the associated environment from the global to the "export" environment for functions exported via ".export", and seems to have resolved these issues.

这篇关于在foreach循环内找不到函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆