R: how does a foreach loop find a function that should be invoked? R: how does a foreach loop find a function that should be invoked? r r

R: how does a foreach loop find a function that should be invoked?


They behave differently because registerDoParallel registers an mclapply backend on Linux, while it registers a clusterApplyLB backend on Windows. When using an mclapply backend, there are essentially no data exporting issues, so it works on Linux. But with clusterApplyLB, you can run into problems if foreach doesn't auto-export the functions and data that are needed.

You can solve this problem by modifying FUN3 to export FUN via the .export option:

FUN3 <- function(a, b) {  foreach(i=1:3, .export='FUN') %dopar% FUN(i, a, b)}

This solution works on both Linux and Windows, since .export is ignored by the mclapply backend.

As pointed out by Hong Ooi, you have an error in your use of clusterExport, but I wouldn't use clusterExport to solve the problem since it is backend specific.


In your clusterExport call, remove the env=environment() part. What you're doing is telling clusterExport to look for your objects in a brand new environment, so naturally it doesn't find them.