R Break and Next
The break statement stops a loop immediately, while the next statement skips the rest of the current iteration and moves on to the following one, giving you fine control over how a loop runs.
Stopping a loop early with break
Normally a loop runs until its condition is false (while) or its sequence is exhausted (for). break interrupts that early: as soon as R executes break, it exits the loop immediately, skipping any remaining iterations, and continues with the code after the loop.
Example: break
numbers <- c(4, 9, 15, 22, 7, 3)
for (n in numbers) {
if (n %% 2 != 0) {
cat("Found the first odd number:", n, "\n")
break
}
}Skipping an iteration with next
next works differently: it doesn't end the loop, it just ends the current pass through the body early and jumps straight to the next iteration, re-checking the loop's condition or moving to the next element of the sequence.
Example: next
for (n in 1:10) {
if (n %% 2 == 0) {
next
}
cat(n, "is odd\n")
}Using break and next together
Combining break and next
total <- 0
for (n in c(5, -2, 8, -1, 12, 40)) {
if (n < 0) {
next
}
total <- total + n
if (total > 20) {
break
}
}
cat("Final total:", total, "\n")- Stop searching as soon as a match is found (break)
- Skip invalid or unwanted values while keeping the loop going (next)
- End a loop once a running total or counter passes a limit (break)
- Filter out certain cases without writing a large nested if-else (next)
Used sparingly, break and next can make loops easier to read than deeply nested if statements, because they let you handle special cases up front and keep the main logic of the loop uncluttered.
Exercise: R Loops
What does the next statement do inside an R loop?