Loops in R Programming
Introduction
Loops are used to execute a block of code repeatedly. In R, there are three main types of loops: for, while, and repeat. This tutorial provides examples for each type of loop.
1. for Loop
The for loop iterates over a sequence (e.g., vector, list) and executes the code block for each element.
Syntax:
for (variable in sequence) {
# Code to execute
}
Example:
# Print numbers from 1 to 5
for (i in 1:5) {
print(i)
}
2. while Loop
The while loop executes a block of code as long as the condition is TRUE.
Syntax:
while (condition) {
# Code to execute
}
Example:
# Print numbers from 1 to 5
x <- 1
while (x <= 5) {
print(x)
x <- x + 1
}
3. repeat Loop
The repeat loop executes a block of code indefinitely until explicitly exited using the break statement.
Syntax:
repeat {
# Code to execute
if (condition) {
break
}
}
Example:
# Print numbers from 1 to 5
x <- 1
repeat {
print(x)
x <- x + 1
if (x > 5) {
break
}
}
4. Nested Loops
Loops can be nested inside each other to perform more complex operations.
Example:
# Print a multiplication table
for (i in 1:3) {
for (j in 1:3) {
print(paste(i, "x", j, "=", i * j))
}
}
5. Using next and break
The next statement skips the current iteration, and the break statement exits the loop.
Example:
# Skip even numbers and stop at 7
for (i in 1:10) {
if (i %% 2 == 0) {
next
}
if (i > 7) {
break
}
print(i)
}
Conclusion
Loops are essential for automating repetitive tasks in R. Depending on the use case, you can choose for, while, or repeat loops to handle different scenarios effectively.