[R-sig-hpc] foreach: using either %do% or %dopar% depending on condition

Stephen Weston stephen.b.weston at gmail.com
Mon May 3 13:22:30 CEST 2010


You could try something like this:

    > '%my%' <- if (hpc == "none") get('%do%') else get('%dopar%')

However, why not just let the user decide by either registering a parallel
backend or not?  The main purpose of the "registerDoSEQ" function is
to allow the user to say that parallel operations should be done sequentially.
The '%dopar%' function is the programmer's way to declare that the
foreach loop can be executed in parallel.  It's the user's job to declare
how the '%dopar%' should be executed.  That also simplifies the code
by not having to define and pass around yet another option to your
functions.

- Steve




On Mon, May 3, 2010 at 6:45 AM, mat <matthieu.stigler at gmail.com> wrote:
> Hi
>
> I wish to be able to substitute %do% or %dopar% depending on whether the
> user wants or not to use the parallel feature. For this, I would do
> something like:
>
> if(hpc) foreach(icount(5), .combine = "rbind")  %dopar%
> else foreach(icount(5), .combine = "rbind")  %do%
>   statement of function...
>
> I did not succeed in doing it, I tried:
>
> foreach(icount(5), .combine = "rbind")  %do% else  %dopar% {
> a<-runif(1)
> b<-runif(1)
> c(a,b)
> }
>
> Or tried to assign outside the operator:
>
> "%my%" <-function(obj,ex) if(hpc=="none") "%dopar%" else "%dopar%"
>
> foreach(icount(5), .combine = "rbind")  %my% {
> a<-runif(1)
> b<-runif(1)
> c(a,b)
> }
>
> But it fails... any idea?
>
> Thanks a lot!!
>
> Matthieu
>



More information about the R-sig-hpc mailing list