while Loops

In this lesson, we will learn all about the while loop in R language.

The simplest kind of loop in the R language is the while loop.

It is simply translated as: "if the given condition is satisfied then execute the statements in the while block and if the condition is not satisfied break the loop (which means the block of code in the curly brackets { } will not be executed).

Syntax of a while loop

The syntax for while loop in R:

while(condition)
{
  statements
}

Let’s take an example of while loop.

Press + to interact
myNumber <- 1
while (myNumber <= 10)
{
print(myNumber)
myNumber = myNumber + 1;
}

In the above code, the condition myNumber <= 10 tells the compiler how many times the statements inside the {} needs to be repeated. Here, each time the variable myNumber is increased by 1. Therefore, the entire loop will run 10 times, each time printing the new value of myNumber. Let’s have a look at the flow of the program:

widget

In a while loop, a block of statements is executed repeatedly until the condition provided to it evaluates to FALSE.

if..else statement inside while loop

Suppose we want to modify our original example, but this time we want to print “even” for numbers that are even and print “odd” for odd numbers. We are still handling numbers from 11 to 1010.

Let’s illustrate our problem:

widget

Mapping this to code is easy:

Press + to interact
myNumber <- 1
while (myNumber <= 10)
{
if(myNumber %% 2 == 0)
{
print("even")
} else
{
print("odd")
}
myNumber = myNumber + 1
}

In the above code snippet, we have a conditional statement inside a loop. In each iteration of the loop, the condition in the if statement evaluates to either true or false. Accordingly, either “even” or “odd” is displayed on the screen.