Note that there are some explanatory texts on larger screens.

plurals
  1. POExecute foreach loop in parallel or sequentially given a condition
    primarykey
    data
    text
    <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>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload