[R] How do I break a foreach loop?

Xing Qiu xing.qiu at gmail.com
Tue May 3 20:48:05 CEST 2011


Hi,

I've noticed that the usual "break", "next" commands do not work in a
foreach loop, is there a nice way to do that?

A little more detail: I am using foreach to conduct a very time
consuming (may take several days if done sequentially) simulation
study.  The number of simulations is set to 1000.  So the command I am
using looks like this simplified version:

grandsum <- foreach(icount(1000), .combine="+") %dopar% { sim(...) }

In fact, grandsum can never take a value greater than a threshold, say
10.0.  So I want the number of iterations depend on the value of
grandsum.  Say when the grandsum is greater equal to 10.0 the
computation should be terminated to save time.  This is the for loop
version of what is in my mind:

grandsum <- 0
for (i in 1:1000) {
  if (grandsum >= 10.0) break
  else grandsum <- grandsum + sim(...)
}

Is there a way to re-write the above for loop by an equivalent
foreach/dopar loop?

Thanks very much,
Xing



More information about the R-help mailing list