Loops in R
In this tutorial, we will learn about different types of loops in R. We will cover the basics of for, while, and repeat loops.
What is a Loop
A loop is a control flow statement that allows code to be executed repeatedly based on a condition.
![Loops](/images/tutorials/loops.png)
R supports three types of loops: for loops, while loops, and repeat loops.
For Loop
A for loop is used when the number of iterations is known before entering the loop. The syntax for the for loop is:
for (variable in sequence) {
# Code block to be executed
}
While Loop
A while loop is used when the number of iterations is not known beforehand. The syntax for the while loop is:
while (condition) {
# Code block to be executed
}
Repeat Loop
A repeat loop is used to execute a code block repeatedly until a condition is met. The syntax for the repeat loop is:
repeat {
# Code block to be executed
if (condition) {
break
}
}
Example 1: Printing Numbers from 1 to 10 using For Loop
- Use a for loop to print numbers from 1 to 10.
R Program
for (i in 1:10) {
cat(i, ' ')
}
Output
1 2 3 4 5 6 7 8 9 10
Example 2: Printing Numbers from 1 to 5 using While Loop
- Declare an integer variable
i
and initialize it to 1. - Use a while loop to print numbers from 1 to 5.
R Program
i <- 1
while (i <= 5) {
cat(i, ' ')
i <- i + 1
}
Output
1 2 3 4 5
Example 3: Printing Numbers from 1 to 3 using Repeat Loop
- Declare an integer variable
i
and initialize it to 1. - Use a repeat loop to print numbers from 1 to 3.
R Program
i <- 1
repeat {
cat(i, ' ')
i <- i + 1
if (i > 3) {
break
}
}
Output
1 2 3