title: How to parallelize a function for a package in R
body: <p>I would like to parallelize a portion of a package I am working on. Which packages and what syntax should I use to make the package flexible and usable on different architectures? My problem sits in a single <code>sapply()</code> call as shown in this mock code:</p>
  
  <pre><code>.heavyStuff &lt;- function(x) { 
     # do a lot of work
     Sys.sleep(1)
  }
  
  listOfX &lt;- 1:20
  
  userFunc1 &lt;- function(listOfX) {    
    res &lt;- sapply(listOfX, .heavyStuff)
    return(res)
  }
  </code></pre>
  
  <p>Based on different guides, I have concocted the following:</p>
  
  <pre><code>userFunc2 &lt;- function(listOfX, dopar.arg=2) {
    if(requireNamespace("doParallel")) {
      doParallel::registerDoParallel(dopar.arg)
      res &lt;- foreach(i=1:length(listOfX)) %dopar% {
         .heavyStuff(listOfX[[i]])
      }
      names(res) &lt;- names(listOfX)
    } else {
      res &lt;- sapply(listOfX, .heavyStuff)
    }
    return(res)
  }
  </code></pre>
  
  <p>Questions: </p>
  
  <ol>
  <li>Can I safely use such a code in a package? Will it work well on a range of platforms?</li>
  <li>Is there a way to avoid the <code>foreach()</code> construct? I'd much prefer to use a sapply- or lapply-like function. However, the constructs in the parallel library appear to be much more platform specific.</li>
  <li>The above code doesn't work if <code>dopar.arg==NULL</code>, even though <a href="https://cran.r-project.org/web/packages/doParallel/vignettes/gettingstartedParallel.pdf" rel="nofollow noreferrer">the introduction to doParallel says that</a> without any arguments "you will get three workers and on Unix-like systems
  you will get a number of workers equal to approximately half the number of cores on your system."</li>
  </ol>