While Loop in R with Example

A while loop in R is used to repeatedly execute a block of code as long as a specified condition remains TRUE. The loop continues iterating until the condition becomes FALSE. Here’s the basic syntax of a while loop in R:

while (condition) {

Code to be executed


Let’s see an example of using a while loop in R:

Example: Using a while loop to print numbers from 1 to 5

counter ← 1

while (counter <= 5) {
counter ← counter + 1

In this example, the loop starts with counter initialized to 1. The loop continues executing as long as the condition counter <= 5 is TRUE. Inside the loop, the current value of counter is printed, and then counter is incremented by 1. This process continues until counter becomes 6, at which point the condition becomes FALSE, and the loop terminates.


[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

Make sure to include a mechanism to eventually make the loop condition FALSE, otherwise, you could end up in an infinite loop. It’s good practice to have a way to control the loop, such as modifying variables inside the loop or using break statements.

Here’s another example using a while loop to calculate the factorial of a number:

Example: Calculate factorial using a while loop

number ← 5
factorial ← 1
counter ← 1

while (counter <= number) {
factorial ← factorial * counter
counter ← counter + 1

print(paste(“Factorial of”, number, “is”, factorial))