在并行 foreach 循环中使用 source() [英] Using source() within parallel foreach loops

查看:34
本文介绍了在并行 foreach 循环中使用 source()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个玩具示例来说明我的问题.

Here is a toy example to illustrate my problem.

library(foreach)
library(doMC)
registerDoMC(cores=2)

foreach(i = 1:2) %dopar%{
  i + 2
}
[[1]]
[1] 3

[[2]]
[1] 4

到目前为止一切都很好...

So far so good...

但是如果代码 i + 2 保存在文件 addition.R 中并且我使用 source() 调用该文件然后

But if the code i + 2 is saved in the file addition.R and that I call that file using source() then

> foreach(i = 1:2) %dopar%{
+   source("addition.R")
+ }
Error in { : task 1 failed - "object 'i' not found"

推荐答案

我无法完全重现您的玩具,但我遇到了一个类似的问题,我可以通过以下方式解决:

I cannot fully reproduce your toy, but I had a smiliar problem, which I was able to solve by:

source(file, local = TRUE)

它应该在本地环境中解析源,即识别 i.

which should parse the source in the local environment, i.e. recognizing i.

这篇关于在并行 foreach 循环中使用 source()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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