01 / 20

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.

R Programming

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.

next
Skips the current iteration and jumps to the next one. The loop continues running.
break
Immediately exits the entire loop. No more iterations run after this point.

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.

1
Efficiency: avoid unnecessary computations when the answer is already found.
2
Data cleaning: skip invalid or missing values gracefully with next.
3
Safety: prevent errors or infinite loops by exiting when a boundary is reached.

Visualizing Loop Flow

Normal Loop Start Loop Execute Body Execute Body Execute Body End With next Start Loop Execute Body next (skip!) Execute Body End With break Start Loop Execute Body break (exit!) End Skipped

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.

for (i in 1:5) { if (i == 3) { next # skip when i is 3 } print(i) }

The break Statement

When R encounters break, it immediately terminates the entire loop. Execution continues with the first statement after the loop.

for (i in 1:5) { if (i == 3) { break # exit when i is 3 } print(i) }

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

1
Identify the condition: What should trigger skipping or stopping? Write a clear if statement.
2
Choose next or break: Need to skip one item? Use next. Need to stop entirely? Use break.
3
Place it inside the if block: The next or break goes inside the if (...) { } block, not after it.
4
Put remaining code after the if: Code you want to run on "normal" iterations goes after the if-next/break block.
5
Test with a small sequence: Try your loop with values like 1:5 and print each step to verify the flow.

Example 1: Skipping Even Numbers

Print only odd numbers from 1 to 8 using next:

for (i in 1:8) { if (i %% 2 == 0) { next # skip even numbers } print(i) }
1 2 skip 3 4 skip 5 6 skip 7 8 skip

Example 2: Finding the First Match

Search a vector for the first negative number and stop:

vals <- c(4, 7, 2, -1, 5, -3) for (v in vals) { if (v < 0) { cat("Found:", v, "\n") break } }
4 ✓ ok 7 ✓ ok 2 ✓ ok -1 break! 5 -3

Example 3: Using Both Together

Process scores: skip invalid values (NA) with next, and stop if a perfect score is found with break:

scores <- c(85, NA, 92, 100, 78) for (s in scores) { if (is.na(s)) { next # skip missing data } if (s == 100) { cat("Perfect score found!\n") break # stop searching } cat("Score:", s, "\n") }

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!

i <- 0 while (i < 6) { i <- i + 1 # increment BEFORE next! if (i == 3) { next } print(i) }

break Only Exits One Level

In nested loops, break only exits the innermost loop it's inside. The outer loop keeps running.

for (i in 1:3) { for (j in 1:3) { if (j == 2) break cat(i, j, "\n") } }
Outer loop (i) i = 1 j=1: print j=2: break j=3: skipped i = 2 j=1: print j=2: break j=3: skipped i = 3 j=1: print j=2: break j=3: skipped

Common Mistakes to Avoid

✕ Infinite Loop with next
In a while loop, placing next before the counter update causes the variable to never change, creating an infinite loop.
✕ Using break Outside a Loop
Calling break or next outside of a for, while, or repeat block causes an error: "no loop for break/next."
✕ Expecting break to Exit All Loops
In nested loops, break only exits the innermost loop. Use a flag variable or restructure the code to exit multiple levels.

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?

for (i in 1:5) { if (i == 4) next cat(i, " ") }

Question 2 of 5

What is the output of this R code?

for (i in 1:5) { if (i == 4) break cat(i, " ") }

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?

i <- 0 while (i < 5) { if (i == 2) next i <- i + 1 }