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

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

问题描述

我正在尝试使用 foreach 在 R 中进行多核计算.

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

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

然后我在控制台中调用函数A.问题是我在 B 中调用了一个函数 Posdef ,该函数是在我提供的另一个脚本文件中定义的.我不得不将 Posdef 放在 foreach 的导出参数列表中:.export=c("Posdef").但是我收到以下错误:

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""

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

Why cant R find this defined function?

推荐答案

简短的回答是这是并行后端中的一个错误,例如 doSNOWdoParalleldoMPI,但它已被修复.

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

稍微长一点的答案是 foreach 使用特殊的导出"环境而不是全局环境将函数导出给工作程序.这曾经导致在全局环境中创建的函数出现问题,因为导出"环境不在它们的范围内,即使它们现在是在同一个导出"环境中定义的.因此,他们看不到导出"环境中定义的任何其他函数或变量,例如您的情况下的Posdef".

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.

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

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天全站免登陆