A Simple Introduction to While Loops in R (With Examples)

This tutorial explains how to create a while loop in R along with several examples.

What is a While Loop?

while loop is a loop that runs a chunk of code over and over until a certain condition is met. The basic syntax for writing a while loop in R is as follows:

while (condition) {
  expression
}

where

  • condition: some condition that tells R when to stop the while loop
  • expression: a chunk of code that does something

The main difference between a while loop and a for loop is the following:

  • for loop is used when the number of iterations a code should be run is known.
  • while loop is used when the number of iterations a code should run is not known.

Examples of While Loops

The following examples illustrate while loops in action.

Example 1

The following while loop defines x as being equal to 1, then prints every incremental value of until we hit the number 10:

#define starting number
x <- 1

#print every number from 1 to 10
while (x <= 10) {
  print(x)
  x <- x + 1
}

#[1] 1
#[1] 2
#[1] 3
#[1] 4
#[1] 5
#[1] 6
#[1] 7
#[1] 8
#[1] 9
#[1] 10

It’s important to include the last line in the expression x <- x + 1, because otherwise x will always be equal to 1 and R will just keep printing “1” over and over again forever.

Example 2

This while loop does something similar to the previous while loop, except it increments x by 2 each time, thus only printing every other number from 1 to 10:

#define starting number
x <- 1

#print every other number from 1 to 10
while (x <= 10) {
  print(x)
  x <- x + 2
}

#[1] 1
#[1] 3
#[1] 5
#[1] 7
#[1] 9

Example 3

The following while loop does something slightly more interesting: it assumes that a variable starts with a value of 1. Then, it simulates a coin being flipped. If the coin lands on heads, the value of the variable increases by 1. If the coin lands on tails, the value of the variable increases by 2. Then, the while loop sees how many flips it takes for the variable to exceed 100:

#define variable to keep track of coin flips
flips <- 1

#define variable to increment 
x <- 1

#create while loop to keep "flipping" coin until x exceeds 100
while(x <= 100 ) {
  coin <- rbinom(1, 1, 0.5)
        
  if(coin == 1) {
                x <- x + 1
        } else {
                x <- x + 2
        }

        flips <- flips + 1
}

paste("It took", flips, "flips to exceed 100.")

#[1] "It took 68 flips to exceed 100."

Note that each time this code is run, the number of flips it takes for the variable to exceed 100 will (likely) be different each time.

A while loop is exactly what we need to use for this particular experiment because we don’t know beforehand how many flips it will take to exceed 100. Thus, we simply tell R to keep “flipping” the coin while x < 100.

Example 4

The following while loop does something similar, but slightly different than the previous example: it assumes that a variable starts with a value of 50. Then, it simulates a coin being flipped. If the coin lands on heads, the value of the variable increases by 1. If the coin lands on tails, the value of the variable decreases by 1. Then, the while loop sees how many flips it takes for the variable to fall below 45 or rise above 55:

#define variable to keep track of coin flips
flips <- 1

#define variable to increment 
x <- 50

#create while loop to keep "flipping" coin until x exceeds 45 or 55
while(x >= 45 && x <= 55) {
  coin <- rbinom(1, 1, 0.5)
        
  if(coin == 1) {
                x <- x + 1
        } else {
                x <- x - 1
        }

        flips <- flips + 1
}

paste("It took", flips, "flips to fall below 45 or rise above 55.")

#[1] "It took 57 flips to fall below 45 or rise above 55.""

Once again, a while loop is exactly what we need to use for this particular experiment because we don’t know beforehand how many flips it will take for the variable to fall below 45 or rise above 55. Thus, we simply tell R to keep “flipping” the coin while x is greater than or equal to 45 and less than or equal to 55.

Further Reading:
How to Create a For Loop in R and Append Results to a Vector

Leave a Reply

Your email address will not be published. Required fields are marked *