[R] if(...){next} with "foreach" loop?

Duncan Murdoch murdoch.duncan at gmail.com
Tue Feb 11 12:43:16 CET 2014


On 14-02-11 5:30 AM, Marc Marí Dell'Olmo wrote:
> Dear all,
>
> I want to do a loop with foreach. But, I would like to include a condition
> with "next" to don't loop over some elements.
>
> For example, I would like to translate this "for loop" to a "foreach loop":
>
> for (i in 1:10) {
>    for (j in 1:2) {
>    ...
>    if((i==2 & j==1) | (i==4 & j==3)) { next }
>    ...
>    }
> }
>
> Foreach loop???
>
> foreach (i = c(1:10)) %do%{
>    foreach (j = c(1:2)) %do%{
>
> #I don't know how to include a "next"!!
> ...
>
>    }
> }

I don't know the foreach package; you might want to direct your 
questions to its maintainer.  But you can always emulate next using an 
if(), e.g. with a regular for loop,

for (i in 1:10) {
   if (cond) next
   ...
}

is the same as

for (i in 1:10) {
   if (!cond) {
     ...
   }
}

My vague understanding of the idea behind the foreach package is that 
the different runs through the loop can be run independently so they can 
be parallelized.  If that's the case, you might be able to evaluate cond 
for each i before the loop starts, and then do the equivalent of

for (i in (1:10)[!cond]) {
   ...
}

Duncan Murdoch

>
> Thank you!
>
> Marc
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list