While loop in R

While loop in R is similar to while loop in any other programming language, which repeat the specific block of code until the condition is no longer satisfied. In brief While loop in R is used to loop until a specific condition is met.

Syntax of while loop in R:

while (condition)
{
statement
}

 

  • First the condition is evaluated and only when it holds TRUE, While loop enters the body.
  • The statements inside the loop are executed and the flow returns to evaluate the condition again.

This is repeated until condition evaluates to FALSE, once the condition holds FALSE, the while loop is exited.

While loop in R

 

 

Example of While loop in R:

In this example we used simple while loop in R, to compute the square of numbers till 6.

# while loop in R

i <- 1
while (i <=6) {
print(i*i)
i = i+1
}

In the above example, i is initially initialized to 1. Here, the test_expression is i <= 6 which evaluates to TRUE since 1 is less than 6. So, the body of the loop is entered and i*i is printed and incremented.

Incrementing i is important as this will eventually meet the exit condition. Failing to do so will result into an infinite loop.

In the next iteration, the value of i is 2 and the loop continues.

This will continue till i takes the value 7. The condition 7 < 6 will give FALSE and the while loop finally exits.

Output:

[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
[1] 36

 

Example: while loop in R with Break statement:

break statement will end the loop abruptly. Once the break statement is read, the loop will be terminated.

# R while loop with break statement

i <- 1
while (i <= 6) {
if (i==4)
break;
print(i*i)
i = i+1
}

Once the value reaches i=4, then the break statements terminates the loop. So only the square of values from 1 to 3 is printed

Output:

[1] 1
[1] 4
[1] 9

 

 

Example: while loop in R with Next statement:

Next statement will skip one step of the loop. Once the next statement is read, the loop will skip the while once.

# while loop in R with next statement

i <- 1
while (i <= 6) {
if (i==4)
{
i=i+1
next;
}
print(i*i);
i = i+1;
}

Once the value reaches i=4, then the next statement skips the loop and the square of 4 i.e 16 is not printed

Output:
[1] 1
[1] 4
[1] 9
[1] 25
[1] 36

previous small while loop in r                                                                                                           next small while loop in r

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.