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

查看:92
本文介绍了在并行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天全站免登陆