How to Use next in R: Skip to Next Loop Iteration
In R, use the
next statement inside loops to skip the current iteration and move to the next one immediately. It helps control loop flow by ignoring certain cases without stopping the entire loop.Syntax
The next statement is used inside loops like for, while, or repeat. When R encounters next, it skips the rest of the current loop body and jumps to the next iteration.
Basic syntax:
for (variable in sequence) {
if (condition) {
next
}
# other code
}Here, if condition is true, next skips to the next loop cycle.
r
for (i in 1:5) { if (i == 3) { next } print(i) }
Output
[1] 1
[1] 2
[1] 4
[1] 5
Example
This example shows how next skips printing the number 3 in a loop from 1 to 5.
r
for (i in 1:5) { if (i == 3) { next } print(i) }
Output
[1] 1
[1] 2
[1] 4
[1] 5
Common Pitfalls
One common mistake is using next outside loops, which causes an error because next only works inside loops.
Another is forgetting that next skips the rest of the loop body, so any code after next in the same iteration won't run.
r
x <- 1 # Wrong usage - next outside loop # next # This will cause an error # Correct usage inside a loop for (i in 1:3) { if (i == 2) { next } print(i) }
Output
[1] 1
[1] 3
Quick Reference
- Use inside loops only:
for,while,repeat. - Purpose: Skip current iteration and continue with next.
- Effect: Code after
nextin the loop body is not executed for that iteration. - Common use: Skip unwanted cases or errors without stopping the loop.
Key Takeaways
Use
next inside loops to skip the current iteration and continue with the next one.next must be inside a loop; using it outside causes errors.Code after
next in the same iteration will not run.It helps handle special cases without stopping the entire loop.
Commonly used in
for, while, and repeat loops.