title: Execute foreach loop in parallel or sequentially given a condition
body: <p>I often end up with several nested <code>foreach</code> loops and sometimes when writing general functions (e.g. for a package) there is no level which is obvious to parallelize at. Is there any way to accomplish what the mock-up below describes?</p>
  
  <pre><code>foreach(i = 1:I) %if(I &lt; J) `do` else `dopar`% {
      foreach(j = 1:J) %if(I &gt;= J) `do` else `dopar`% {
          # Do stuff
      }
  }
  </code></pre>
  
  <p>Furthermore, is there some way to detect if a parallel backend is registered so I can avoid getting unnecessary warning messages? This would be useful both when checking packages prior to CRAN submission and to not bother users running R on single core computers.</p>
  
  <pre><code>foreach(i=1:I) %if(is.parallel.backend.registered()) `dopar` else `do`% {
      # Do stuff
  }
  </code></pre>
  
  <p>Thanks for your time.</p>
  
  <p><strong>Edit:</strong> Thank you very much for all the feedback on cores and workers and you're right in that the best way to deal with the above example would be to rethink the whole setup. I'd prefer something like to below to the <code>triu</code> idea but it's essentially the same point. And it could of course also be done with a parallel <code>tapply</code> like Joris suggested.</p>
  
  <pre><code>ij &lt;- expand.grid(i=1:I, j=1:J)
  foreach(i=ij$I, j=ij$J) %dopar% {
      myFuction(i, j)
  }
  </code></pre>
  
  <p>However, in my attempt to simplify the situation that gave rise to this thread I left out some crucial details. Imagine that I have two functions <code>analyse</code> and <code>batch.analyse</code> and the best level to parallelize at might be different depending on the values of <code>n.replicates</code> and <code>n.time.points</code>. </p>
  
  <pre><code>analyse &lt;- function(x, y, n.replicates=1000){
      foreach(r = 1:n.replicates) %do% {
          # Do stuff with x and y
      }
  }
  batch.analyse &lt;- function(x, y, n.replicates=10, n.time.points=1000){
      foreach(tp = 1:time.points) %do% {
          my.y &lt;- my.func(y, tp)
          analyse(x, my.y, n.replicates)
      }
  }
  </code></pre>
  
  <p>If <code>n.time.points &gt; n.replicates</code> it makes sense to parallelize in <code>batch.analyse</code> but otherwise it makes more sense to parallelize in <code>analyse</code>. Any ideas on how to tackle it? Would it somehow be possible to detect in <code>analyse</code> if parallelization has already taken place? </p>