repeat
repeat keeps going forever until you tell it to stop, like a merry-go-round that runs until someone pulls the brake. The brake is a break command.
In this page:
Syntax
repeat {
# body
if (condition) break
}
repeat
repeat runs its body indefinitely with no built-in condition, relying entirely on a break statement inside to stop.
This is R's equivalent of an unconditional infinite loop found in other languages (like while (true) in C-family languages). It's most useful when the exit condition is checked partway through the loop body rather than at the very start.
Note:
repeat is the right choice when you need to check the exit condition somewhere in the middle of the loop body, not just at the top.
Example: repeat
count <- 1
repeat {
cat("Count:", count, "\n")
count <- count + 1
if (count > 3) {
break
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Omitting
break, sorepeatruns forever. - Putting the counter update after the
if (... ) break, so the loop stops one iteration too late. - Using
repeatwhen awhilewith a clear condition would be easier to read.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: