next & break
Master the two essential loop control statements in R that let you skip iterations and exit loops early for cleaner, more efficient code.
What Are Loop Control Statements?
When a loop runs in R, it normally executes every iteration from start to finish. But sometimes you need to change this default behavior: skip certain values or stop the loop entirely when a condition is met.
Why Do We Need Them?
Imagine searching through a dataset of 1 million rows. Without loop control, your code must check every single row, even after finding the answer. With break, you stop immediately. With next, you skip irrelevant data.
Visualizing Loop Flow
The next Statement
When R encounters next inside a loop, it immediately stops executing the rest of the loop body for the current iteration and jumps to the next value in the sequence.
The break Statement
When R encounters break, it immediately terminates the entire loop. Execution continues with the first statement after the loop.
next vs break: The Key Difference
| next | break | |
|---|---|---|
| Effect | Skips one iteration | Exits the entire loop |
| Loop continues? | Yes | No |
| Analogy | Skip a song on a playlist | Turn off the music player |
| Common use | Filter out bad data | Stop searching once found |
| Code after it | In that iteration: skipped | All remaining: skipped |
How to Apply Loop Control
Example 1: Skipping Even Numbers
Print only odd numbers from 1 to 8 using next:
Example 2: Finding the First Match
Search a vector for the first negative number and stop:
Example 3: Using Both Together
Process scores: skip invalid values (NA) with next, and stop if a perfect score is found with break:
next in while Loops
Both statements also work in while and repeat loops. Be careful: you must update your counter before calling next, or you'll create an infinite loop!
break Only Exits One Level
In nested loops, break only exits the innermost loop it's inside. The outer loop keeps running.
Common Mistakes to Avoid
Summary Reference Table
| next | break | |
|---|---|---|
| Syntax | next | break |
| Scope | Current iteration only | Entire loop |
| Loop after call | Continues to next i | Stops completely |
| Works in for? | Yes | Yes |
| Works in while? | Yes | Yes |
| Nested behavior | Affects innermost loop | Exits innermost loop |
| Python equivalent | continue | break |
Question 1 of 5
What is the output of this R code?
Question 2 of 5
What is the output of this R code?
Question 3 of 5
Which statement correctly describes the difference between next and break in R?
Question 4 of 5
What happens when break is used inside a nested loop in R?
Question 5 of 5
What is the risk of using next inside a while loop?