title: Is there any way to break out of a foreach loop?
body: <p>I am using the R package <code>foreach()</code> with <code>%dopar%</code> to do long (~days) calculations in parallel. I would like the ability to stop the entire set of calculations in the event that one of them produces an error. However, I have not found a way to achieve this, and from the documentation and various forums I have found no indication that this is possible. In particular, <code>break()</code> does not work and <code>stop()</code> only stops the current calculation, not the whole <code>foreach</code> loop.</p>
  
  <p>Note that I cannot use a simple for loop, because ultimately I want to parallelize this using the doRNG package.</p>
  
  <p>Here is a simplified, reproducible version of what I am attempting (shown here in serial  with <code>%do%</code>, but I have the same problem when using <code>doRNG</code> and <code>%dopar%</code>). Note that in reality I want to run all of the elements of this loop (here 10) in parallel.</p>
  
  <pre><code>library(foreach)
  myfunc &lt;- function() {
    x &lt;- foreach(k = 1:10, .combine="cbind", .errorhandling="stop") %do% {
      cat("Element ", k, "\n")
      Sys.sleep(0.5) # just to show that stop does not cause exit from foreach
      if(is.element(k, 2:6)) {
        cat("Should stop\n")
        stop("Has stopped")
      }
      k
    }
    return(x)
  }
  x &lt;- myfunc()
  # stop() halts the processing of k=2:6, but it does not stop the foreach loop itself.
  # x is not returned. The execution produces the error message
  # Error in { : task 2 failed - "Has stopped"
  </code></pre>
  
  <p>What I would like to achieve is that the entire foreach loop can be exited immediately upon some condition (here, when the <code>stop()</code> is encountered).</p>
  
  <p>I have found no way to achieve this with <code>foreach</code>. It seems that I would need a way to send a message to all the other processes to make them stop too.</p>
  
  <p>If not possible with <code>foreach</code>, does anyone know of alternatives? I have also tried to achieve this with <code>parallel::mclapply</code>, but that does not work either.</p>
  
  <pre><code>&gt; sessionInfo()
  R version 3.0.0 (2013-04-03)
  Platform: x86_64-apple-darwin10.8.0 (64-bit)
  
  locale:
  [1] C/UTF-8/C/C/C/C
  
  attached base packages:
  [1] stats     graphics  grDevices utils     datasets  methods base
  
  other attached packages:
  [1] foreach_1.4.0
  
  loaded via a namespace (and not attached):
  [1] codetools_0.2-8 compiler_3.0.0  iterators_1.0.6
  </code></pre>