How to Use break in R: Simple Loop Control Explained
In R, use the
break statement inside loops like for or while to immediately stop the loop and exit it. This helps when you want to end the loop early based on a condition.Syntax
The break statement is used inside loops to stop the loop immediately and continue with the code after the loop.
It has no arguments and is simply written as break.
r
for (i in 1:10) { if (i == 5) { break } print(i) }
Output
1
2
3
4
Example
This example shows a for loop that prints numbers from 1 to 10 but stops when the number reaches 5 using break.
r
for (i in 1:10) { if (i == 5) { break } print(i) }
Output
[1] 1
[1] 2
[1] 3
[1] 4
Common Pitfalls
- Using
breakoutside a loop causes an error because it only works inside loops. - Placing
breakafter code inside the loop means that code runs before the loop stops. - For nested loops,
breakonly exits the innermost loop.
r
x <- 1 # Wrong: break outside loop # break # This will cause an error # Correct usage inside loop for (i in 1:3) { if (i == 2) { break } print(i) }
Output
[1] 1
Quick Reference
break statement quick tips:
- Use inside
for,while, orrepeatloops. - Stops the current loop immediately.
- Does not affect outer loops in nested loops.
- No arguments needed, just write
break.
Key Takeaways
Use
break inside loops to stop them early based on a condition.break only works inside loops and stops the innermost loop.Avoid using
break outside loops to prevent errors.In nested loops,
break exits only the current loop, not all loops.