R Loop Structure

These are the three loop control structures of R -

  • repeat loop
  • while loop
  • for loop

R repeat loop

Repeat loop is the easiest loop in R. It is similar to the do-while loop of other languages. In this, the conditional check is written at the end of the loop iteration, so the statement is executed first before the condition is tested.

Syntax of R repeat loop

repeat{
    statements
}

Example of R repeat loop

In the example below, we use the repeat loop to print numbers and exit the loop when x equals to value 10.

> x <- 1
> repeat {
+ print(x)
+ x = x+1
+ if(x == 10) {
+ break
+ }
+ }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9




R while loop

While loop is used for iteration. In each iteration, it evaluates the truth expression just like the If statement. If the condition evaluates to true, then the statement inside the loop is executed and control goes to the next iteration. If the condition evaluates to false, then the loop ends and control goes out of the loop.

Syntax of R while Loop

while(condition){
    statements
}

Example of R while Loop

In the example below, we use the while loop to print numbers until the condition within the loop fulfill.

> n <- 0
> while(n < 6){
+ print(n)
+ n <- n+1
+ }
[1] 0
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

R for loop

For loop executes the same code given number of times. It contains a iterator variable and a vector.

Syntax of the for loop

for(value in vector){
    statement;
}

Example of the for loop

In the example below, we use the for loop to print numbers unto the given number of series.

x <- c(1:5)
> for(i in x){
+ print(i)
+ }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5