How to use a while loop in R
A while loop is a block of code that can be repeatedly executed given the condition needed to execute it, returns true. Hence, the code runs in a loop as long as the condition holds.
Understanding the while loop
The first step to writing a loop is to understand the logic behind it. The illustration below shows the workings of a while loop:
Syntax
The next step is to understand the syntax of a while loop in R. The code snippet below shows how to code a while loop in R.
The condition_statement is a single condition or a set of multiple conditions that return a boolean value of true or false.
If the returned value is true only then will the loop execute the code inside it.
while(condition_statement){#Loop body goes here}
Examples
Now that we know how a while loop works and its syntax, let’s look at a few examples to better understand how to use it in R.
1. Will the loop even execute?
This example shows what happens when the condition statement is false from the start. The code inside the loop body is not executed and the program moves on to the code outside the while block.
iterator <- 10while(iterator>11){print("In while loop")iterator <- iterator + 1}print("Outside while loop")
2. Using a single condition
This while loop, in the example below, has a condition statement based on an incrementing numeric value. When the value of the iterator exceeds 10, it should break.
iterator <- 1while(iterator<=10){print(iterator)iterator <- iterator + 1}print("Outside while loop")
3. Using multiple conditions
This example shows how to use more than one condition in the loop. As seen on line 4 the while loop has two conditions, one using the AND operator and the other using the ORoperator.
Note: The
ANDcondition must be fulfilled for the loop to run. However, if either of the conditions on theORside of the operator returnstrue, the loop will run.
iterator <- 1second_iterator <- 10third_iterator <-1while(third_iterator <=4 && iterator<=10 || second_iterator<5){cat("First Iterator: ", iterator, "\n")cat("Second iterator: ",second_iterator, "\n")cat("Third iterator: ",third_iterator, "\n")iterator <- iterator + 1second_iterator <- second_iterator + 1third_iterator <- third_iterator + 1}print("Outside while loop")
Free Resources