While Loop

R While loop has a condition and a body. While Loop executes a set of statements in the body repeatedly in a loop as long as the condition is satisfied. We shall learn about the syntax, execution flow for While Loop with examples.

Syntax – While Loop

The syntax of While Loop in R is

while (expression) {
     statement(s)
}
ADVERTISEMENT

Execution Flow

The flow of execution is depicted in the following picture.

R While Loop

As long as the boolean expression evaluates to TRUE, the statements inside the while block are executed. The point at which the boolean expression results FALSE, the execution flow is out of the while loop statement.

Examples

A Simple While Loop to Print Numbers from 1 to N

In this example, we will use while loop and print numbers from 1 to 4.

r_while_loop_ex.R

a <- 1

while(a<5) {
  print(a)
  a = a+1
}

Output

~$ Rscript r_while_loop_ex.R 
[1] 1
[1] 2
[1] 3
[1] 4

Break statement inside While Loop

Not only the boolean expression next to while keyword could stop the while loop, but also a break statement kept intentionally inside the while loop. An example is provided below.

r_while_loop_break_ex.R

a <- 1
b <- 3

while(a<5) {
  if (a == b) {
    break
  }
  print(a)
  a = a+1
}

Output

~$ Rscript r_while_loop_break_ex.R 
[1] 1
[1] 2

The inclusion of break statement might look similar to R Repeat Loop Statement.

Conclusion

In this R Tutorial, we have learnt about the syntax and execution flow of while loop with R example scripts.