How to Use Repeat Loop in R: Syntax and Examples
In R, a
repeat loop runs code repeatedly until you explicitly stop it using break. It has no built-in condition, so you must use break inside the loop to exit it.Syntax
The repeat loop syntax in R is simple. You write repeat followed by curly braces {} containing the code to repeat. To stop the loop, use break inside the braces when a condition is met.
- repeat: starts the loop
- { }: contains the code block to repeat
- break: exits the loop when called
r
repeat {
# code to repeat
if (condition) {
break
}
}Example
This example shows a repeat loop that counts from 1 to 5 and then stops using break.
r
count <- 1 repeat { print(count) if (count >= 5) { break } count <- count + 1 }
Output
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Common Pitfalls
A common mistake is forgetting to include a break statement, which causes an infinite loop that never stops. Always ensure your loop has a clear exit condition.
Wrong way (infinite loop):
r
count <- 1 repeat { print(count) count <- count + 1 # Missing break condition }
Quick Reference
- repeat: starts an infinite loop
- break: stops the loop
- Use
ifinside loop to check exit condition - Always include
breakto avoid infinite loops
Key Takeaways
Use
repeat to run code repeatedly until you use break to stop.Always include a
break condition inside the loop to avoid infinite loops.The
repeat loop has no built-in exit condition; you control when it stops.Use
if statements inside the loop to decide when to break.The
repeat loop is useful when you want to loop until a condition is met but donโt know how many times in advance.