In R, the repeat
loop statement functions similarly to the do-while statement in other programming languages. It repeatedly executes a block of statements until a break statement is encountered. Without a break statement, the repeat loop will continue indefinitely, creating an infinite loop.
This statement is mostly used if you wanted to execute the repeated block at least one time.
Below is a flow chart of how the repeat statement works.
1. repeat of Syntax
The following is the syntax of the repeat statement
# repeat syntax
repeat
{
#one or more statements
if( condition )
{
break
}
}
2. repeat Loop Example
Let’s understand the repeat loop statement with an example in R.
# repeat example
i = 1
repeat {
print(i)
i = i + 1
if(i >= 5 )
break
}
# Output
#[1] 1
#[1] 2
#[1] 3
#[1] 4
Conclusion
In this article, you have learned what is repeat loop statement in R and how to use it with an example. The repeat
loop statement in R is similar to do while
statement in other languages. repeat run the block of statements repeatedly until the break jump statement is encountered. You have to use the break statement to terminate or exit the loop. Not using a break will end up repeat statements in an indefinite loop.
Related Articles
- Looping in R (for, while, repeat) With Examples
- For Loop in R with Examples
- While Loop in R with Examples
- Nested For Loop in R
- Break and Next (Continue) Statements in R
- R Using For in Range with Example
- R if, if…else, if…else…if Usage with Examples
- R if…else with Multiple Conditions
- R ifelse() Function