简体   繁体   English

为什么在 foreach 中使用 %dopar% 会导致 R 无法识别 package?

[英]Why is using %dopar% with foreach causing R to not recognize package?

I was trying to get my code to run in parallel on R by using the doParallel package with the foreach package.我试图让我的代码在 R 上并行运行,方法是使用 doParallel package 和 foreach package。 I am also using the sf package to manipulate shp files.我也在使用 sf package 来操作 shp 文件。 I made sure all my code worked in the foreach loop just using %do% so if there was an error I could better track it down.我确保我的所有代码都在 foreach 循环中工作,只使用 %do% 所以如果有错误我可以更好地追踪它。 My code worked fine using foreach and %do% but when I changed it do %dopar% R would keep giving me the following error:我的代码使用 foreach 和 %do% 运行良好,但是当我更改它时,执行 %dopar% R 会继续给我以下错误:

Error in {: task 1 failed - "could not find function "st_geometry_type"" {中的错误:任务 1 失败 - “找不到 function “st_geometry_type””

Even though I clearly use require(sf) at the top of the R script.即使我清楚地在 R 脚本的顶部使用了 require(sf) 。 I made a small function that just prints out "check" if the statement is true to replicate the error.我做了一个小的 function ,如果语句为真以复制错误,它只会打印出“检查”。

require(sf)
require(doParallel)
doParallel::registerDoParallel(cores = 2)

testforeach <- function(sfObject)
{
  foreach(i=1:10) %dopar% {
    if (st_geometry_type(sfObject[i,]) == "LINESTRING")
    {
      print("check")
    }
  }
}

When I run this code it throws the same exact error:当我运行此代码时,它会引发相同的错误:

Error in {: task 1 failed - "could not find function "st_geometry_type"" {中的错误:任务 1 失败 - “找不到 function “st_geometry_type””

However when I replace %dopar% with %do% it prints out all of the expected "check" messages.但是,当我将 %dopar% 替换为 %do% 时,它会打印出所有预期的“检查”消息。 Is this a bug in R or am I missing something?这是 R 中的错误还是我遗漏了什么? I tried reinstalling my packages but that didn't seem to have any affect as I continued to get the same error.我尝试重新安装我的软件包,但这似乎没有任何影响,因为我继续遇到同样的错误。 Any help would be greatly appreciated.任何帮助将不胜感激。

You need to include the packages you will use inside the loop in the foreach function您需要在foreach function 的循环中包含您将使用的包

foreach(i=1:10,.packages="sf") %dopar% {
    if (st_geometry_type(sfObject[i,]) == "LINESTRING")
    {
      print("check")
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM