R Break and Next
The next statement skips the rest of the current round of a loop. The break statement ends the whole loop at once.
Skip the even numbers
The test finds each even number in the run. The next statement skips its print, so only odd numbers appear.
for (n in 1:7) {
if (n %% 2 == 0) {
next
}
print(n)
}Stop at a target
The loop prints numbers until it reaches 4. The break ends the loop at that point.
for (n in 1:10) {
if (n == 4) {
break
}
print(n)
}Break inside a while loop
The test stays true on its own here. A break inside the block stops the loop after 3.
i <- 1
while (TRUE) {
print(i)
i <- i + 1
if (i > 3) {
break
}
}Example
for (n in 1:10) {
if (n %% 3 == 0) {
next
}
if (n > 7) {
break
}
print(n)
}Key points
- The word next jumps straight to the next round.
- Code after next in the block is skipped for that round.
- The word break leaves the loop right away.
- Rounds after a break never run.
- An if test often guards both next and break.
In this example, next skips each number that divides by 3 with no remainder. The break ends the loop when the count passes 7, so print shows 1, 2, 4, 5 and 7.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What does next do inside a loop?