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.

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.

 

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
}
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