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?
Asked
Active
Viewed 156 times
0

Omar Velazquez
- 27
- 4
-
1Please 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
-
1You 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 Answers
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
-
1The sentinel value did the work accurately. Cheers for the suggestion – Omar Velazquez Sep 30 '22 at 09:38
-
1just realised that what I was actually looking for was ```break``` for the inner loop, and then ```next``` for the outer one – Omar Velazquez Sep 30 '22 at 11:28