0

I am running a code with a very large for loop. Within that large loop, I have a second for loop that carries out some checks. If one of those checks is not satisfactory, I am using break to stop the second loop, but instead of continuing with the rest of the lines below, I want the code to go back to the line corresponding to the beginning of the first for loop and carry on the analysis with the next index. Is this possible?

  • 1
    Please post a reproducible example with some code and data as described [here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). It is possible to do what you describe. There may also be a way of writing the code so it is not necessary. – SamR Sep 29 '22 at 17:11
  • 1
    You could wrap the rest of the second loop in a conditional that is skipped when the condition that triggers the break occurs. – John Coleman Sep 29 '22 at 17:16

1 Answers1

1

You can create a sentinel value:

for (OL in ...) {
  # do something
  next_OL <- FALSE         # always set this before entering the inner loop
  for (IL in ...) {
    # do something else
    if (some_condition) {
      next_OL <- TRUE
      break                # breaks out of inner loop "IL"
    }
  }
  if (next_OL) next        # breaks out of outer loop "OL"
  # perhaps do more here
}
r2evans
  • 141,215
  • 6
  • 77
  • 149