Search code examples
rrstudiodoparallelparallel-foreach

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. I am also using the sf package to manipulate shp files. 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. My code worked fine using foreach and %do% but when I changed it do %dopar% R would keep giving me the following error:

Error in { : task 1 failed - "could not find function "st_geometry_type""

Even though I clearly use require(sf) at the top of the R script. I made a small function that just prints out "check" if the statement is true to replicate the error.

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

However when I replace %dopar% with %do% it prints out all of the expected "check" messages. Is this a bug in R or am I missing something? 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.


Solution

  • You need to include the packages you will use inside the loop in the foreachfunction

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