while Loop in R (With Examples)

A loop is a sequence of instructions repeated until a certain condition is reached. A while loop performs the same operation (reruns the code) until a given condition is true.

To stop the loop, there must be a relation between the condition and expression. Otherwise, the loop will never stop, becoming an infinite loop.

Syntax:

while(condition){
expression
}

Example 1: Print index as long as it is less than 10

Here, we have an “Index” variable with a value of 1. The loop will continue to print numbers ranging from 1 to 10. The loop will stop at 10 because 10 < 10 is FALSE. Note that we are incrementing the index value by 1 after each loop.

#creating a variable
index = 1

while(index < 10{    #checking if the condition is true
print(index)         #printing if the condition is true
index = index + 1    #incrementing index by 1
}

Output:

Example 1
While loop to print a variable as long as the condition satisfies.

Example 2: Infinite Loop

To make a loop stop, there must be a relation between the condition and expression. Otherwise, the loop will never stop, becoming an infinite loop. For instance, if we don’t increment the index value in Example 1, it will rerun with the same condition and expression in each loop.

#creating a variable
index = 1

while(index < 10{   #checking if the condition is true
print(index)        #printing if the condition is true
}

Output:

Infinite Loop
Infinite Loop in while loop.

Example 3: Storing value in a vector

In this example, we add the value of a variable “i” in an empty vector “container” until it is less than 10.

#creating an empty vector
container <- c()
#creating a variable
i <- 1
#while loop
while(i<10){                   #checking if the condition is true
container <- c(container, i)   #adding the i value in vector
print(container)               #printing the container vector
i <- i+1                       #incrementing the i value by 1
}

Output:

Example 3
While loop to store data values in a vector.

Was this article helpful?

Leave a Comment