2

I am fairly new to using packages such as "foreach" and "do.parallel". I am now trying to figure out how to break a statement in a nested foreach loop. Here is a simplified example of what I want to do. This is the original for loop that I would like to replicate using foreach (in reality, my code cannot be translated into a while loop as easily, but if there exists such a solution, it might be possible to use a while loop instead):

for (i in 1:30) {
  for (j in 1:40) {
    x <- paste0(i,j)
    print(x)
    if (j >= 30) {
      break
    }
  }
} 

This is my attempt to translate to a foreach. I want to parallelise the outer loop only, but would like to be able to break the inner (sequential) loop once a certain if-condition is satisfied.

(cl <- (detectCores() - 1) %>%  makeCluster(outfile = "")) %>% registerDoParallel

foreach (i = 1:30, .packages = "foreach") %dopar% {
  foreach (j = 1:40) %do% {
    x <- paste0(i,j)
    print(x)
    if (j >= 30) {
      break
    }
  }
}

I have studied other solutions proposed on SO, however, most solutions were much more advanced than the simple case I am looking for.

Thanks!

WillyWonka
  • 107
  • 1
  • 11
  • 3
    Why not just use `for` for the inner loop (instead of `foreach`? That does what you want. That said, I’d *generally* rewrite this code without loops, using `lapply` or `mclapply` instead. – Konrad Rudolph Feb 11 '19 at 14:56
  • Possible duplicate of [Is there any way to break out of a foreach loop?](https://stackoverflow.com/questions/16079882/is-there-any-way-to-break-out-of-a-foreach-loop) – Ben373 Feb 11 '19 at 14:59
  • @KonradRudolph, thanks for the hint! I did not know that it was possible to combine foreach and for, but that did the trick for me. Thanks also for the hint regarding lapply; I am, however, not sure if that would work given that I am using RSelenium for web scraping purposes. – WillyWonka Feb 11 '19 at 15:11
  • @Ben373, sorry for not making this clearer. I have studied that solution before (and maybe I did not fully understand it), but it seems to deal with error handling and writing more complicated functions than I considered necessary for the *simple* case. KonradRudolph 's comment has provided a much easier and clearer answer in my opinion. – WillyWonka Feb 11 '19 at 15:13

0 Answers0