R Break and Next
Break and next are two control statements that change how a loop behaves from inside. Break stops the loop entirely. Next skips the rest of the current iteration and jumps to the next one. Both give you fine-grained control over loop execution.
The break Statement
Diagram:
Loop running...
│
├── Iteration 1 ✓
├── Iteration 2 ✓
├── Iteration 3 → break! ──► EXIT LOOP
├── Iteration 4 (never reached)
└── Iteration 5 (never reached)
for (i in 1:10) {
if (i == 4) break
cat(i, "")
}
Output:
1 2 3
The loop stops the moment i equals 4. Values 4 through 10 are never processed.
Practical break Example: Search in a List
products <- c("pen", "book", "ruler", "eraser", "sharpener")
target <- "ruler"
found <- FALSE
for (i in seq_along(products)) {
if (products[i] == target) {
cat("Found '", target, "' at position", i, "\n")
found <- TRUE
break # no need to keep searching
}
}
if (!found) cat("Product not found\n")
Output:
Found ' ruler ' at position 3
The next Statement
Diagram:
Loop running...
│
├── Iteration 1 ✓ (fully runs)
├── Iteration 2 → next! → skip rest → go to Iteration 3
├── Iteration 3 ✓ (fully runs)
└── Iteration 4 ✓ (fully runs)
for (i in 1:6) {
if (i %% 2 == 0) next # skip even numbers
cat(i, "")
}
Output:
1 3 5
When i is even (2, 4, 6), next jumps to the next iteration. The cat() line never runs for even numbers.
Practical next Example: Skip Missing Values
readings <- c(23, NA, 45, NA, 12, 38, NA, 51)
total <- 0
count <- 0
for (r in readings) {
if (is.na(r)) next # skip missing readings
total <- total + r
count <- count + 1
}
cat("Valid readings:", count, "\n")
cat("Average:", total / count, "\n")
Output:
Valid readings: 5 Average: 33.8
Using break and next Together
for (i in 1:20) {
if (i %% 2 == 0) next # skip even numbers
if (i > 10) break # stop after 10
cat(i, "")
}
Output:
1 3 5 7 9
break Inside Nested Loops
Break only exits the innermost loop it is placed in:
for (i in 1:3) {
for (j in 1:3) {
if (j == 2) break # exits only the inner loop
cat(i, j, " | ")
}
}
Output:
1 1 | 2 1 | 3 1 |
Quick Comparison
Statement Effect on Loop ────────────────────────────────────────────────────── break Stops the loop immediately, exits completely next Skips the current iteration, continues to next
Break is ideal for search operations — stop when you find what you need. Next is ideal for filtering — process only items that meet a condition. Together they make loops much more efficient by avoiding unnecessary processing.
