[R-sig-hpc] programmatically shift between %do% and %dopar% in foreach?

Brian G. Peterson brian at braverock.com
Tue Jan 8 18:10:00 CET 2013


On 01/08/2013 10:40 AM, Max Kuhn wrote:
> I'd like to have the option of using foreach but be able to restrict
> processing to be parallel in one of my packages.
>
> I'd rather not have
>
>     x <- if(goParallel) foreach(stuff) %dopar% foo else foreach(stuff) %do%
> foo
>
> Also, the function is nested within layers that conduct parallel processing
> (i.e. the foo above might also use dopar inside) and my impression is
> that registerDoSEQ would shut down parallel processing for both functions.
>
> It looks like %do% and %dopar% are not existing objects:
>
>     > str(%do%)
>     Error: unexpected SPECIAL in "str(%do%"
>
> Otherwise I would add some conditional logic to switch between them such as
>
>     operator <- if(goParallel) %dopar% else %do%
>      x <- foreach(stuff) operator foo

I always use %dopar%, and if necessary, e.g. in nested foreach loops, 
turn off parallelization on the nested workers after you're inside the 
worker loop, using a simple if construct as you describe.

-- 
Brian



More information about the R-sig-hpc mailing list