title: R: how does a foreach loop find a function that should be invoked?
body: <p>I have problems when I use a foreach loop (using <code>%dopar%</code>) which invokes a self-defined function. There is not really a problem when I work with Linux, but when I use Windows the self-defined function cannot be found. It is hard to explain the problem in words, so I composed a small example to show it. Assume I have a collection of three simple functions, where <code>FUN2</code> (using <code>%do%</code>) and <code>FUN3</code> (using <code>%dopar%</code>) invoke the first one (<code>FUN</code>):</p>
  
  <pre><code>FUN &lt;- function(x,y,z) { x + y + z }
  FUN2 &lt;- function(a, b) {
    foreach(i=1:3) %do% FUN(i, a, b)
  }
  FUN3 &lt;- function(a, b) {
    foreach(i=1:3) %dopar% FUN(i, a, b)
  }
  </code></pre>
  
  <p>The functions are stored in a script called <code>foreach_testfunctions.R</code>. In another script (<code>foreach.test</code>) I source these functions, use <code>library(doParallel)</code> and try to use the functions. First I do it with Linux and all works fine:</p>
  
  <pre><code>source("foreach_testfunctions.R")
  a &lt;- 2
  b &lt;- 3
  library(doParallel)
  registerDoParallel()
  
  foreach(i=1:3) %do% FUN(i, a, b)    ## works fine
  FUN2(a, b)                          ## works fine
  foreach(i=1:3) %dopar% FUN(i, a, b) ## works fine
  FUN3(a, b)                          ## works fine 
  </code></pre>
  
  <p>Then I do it in Windows:</p>
  
  <pre><code>source("foreach_testfunctions.R")
  a &lt;- 2
  b &lt;- 3
  library(doParallel)
  cl &lt;- makeCluster(3)
  registerDoParallel(cl)
  
  foreach(i=1:3) %do% FUN(i, a, b)    ## works fine
  FUN2(a, b)                          ## works fine
  foreach(i=1:3) %dopar% FUN(i, a, b) ## works fine
  FUN3(a, b)                          ## does not work
  Error in FUN(i, a, b) : task 1 failed - "Could not find function "FUN""
  </code></pre>
  
  <p>Conclusion: (1) No problems with <code>%do%</code>. (2) Problems with <code>%dopar%</code> when using Windows. I tried inserting the line <code>clusterExport(cl, varlist=c("FUN", "a", "b"), env=environment())</code> before the line that invokes <code>FUN3</code> to make sure that the function <code>FUN</code> and the variables a and b are found in the proper environment, but the error remains.</p>
  
  <p>My questions: Why does Windows behave different than Linux although the code is identical (apart from the different <code>registerDoParallel</code> syntax)? How can I make sure that Windows <strong>does</strong> find function <code>FUN</code> when invoked via function <code>FUN3</code>? </p>