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!