R Loops – For, While, and Repeat Loops in R Programming
Introduction – Repeating Tasks with Loops in R
When you’re dealing with repetitive tasks, like processing elements of a vector or calculating values in a sequence, loops in R are your go-to solution. R supports three main types of loops:
for– iterate over sequenceswhile– continue while a condition is truerepeat– infinite loop with exit conditions
Loops automate tasks and are fundamental in data processing, simulations, and algorithm building.
In this guide, you’ll learn:
- How to use
for,while, andrepeatloops - Loop control using
breakandnext - Practical examples for iteration and logic
For Loop – Iterate Over a Sequence
The for loop is ideal when you know how many times to run the loop in advance.
Syntax:
for (variable in sequence) {
# code block
}
Example:
for (i in 1:5) {
print(paste("Iteration:", i))
}
Output:
[1] "Iteration: 1"
[1] "Iteration: 2"
[1] "Iteration: 3"
[1] "Iteration: 4"
[1] "Iteration: 5"
While Loop – Repeat While a Condition is TRUE
Use while when the number of iterations is not known in advance.
Syntax:
while (condition) {
# code block
}
Example:
x <- 1
while (x <= 3) {
print(x)
x <- x + 1
}
Output:
[1] 1
[1] 2
[1] 3
♾️ Repeat Loop – Infinite Loop with Manual Exit
The repeat loop runs endlessly unless you use break.
Syntax:
repeat {
# code block
if (exit_condition) break
}
Example:
x <- 1
repeat {
print(x)
x <- x + 1
if (x > 3) break
}
Output:
[1] 1
[1] 2
[1] 3
Controlling Loop Execution
break – Exit the loop early
for (i in 1:5) {
if (i == 3) break
print(i)
}
Output:
[1] 1
[1] 2
⏭️ next – Skip to next iteration
for (i in 1:5) {
if (i == 3) next
print(i)
}
Output:
[1] 1
[1] 2
[1] 4
[1] 5
Looping Over Vectors and Lists
students <- c("Alice", "Bob", "Charlie")
for (name in students) {
print(paste("Hello,", name))
}
Output:
[1] "Hello, Alice"
[1] "Hello, Bob"
[1] "Hello, Charlie"
Summary – Recap & Next Steps
Loops allow you to repeat tasks, iterate over data, and apply logic conditionally. They’re essential for automating processes in data cleaning, calculations, and simulations.
Key Takeaways:
forloops are best for sequences or vectorswhileloops are used when the exit condition is dynamicrepeatloops run until abreakcondition is met- Use
breakto stop a loop,nextto skip an iteration - Loops can iterate over numbers, vectors, and lists
Real-World Relevance:
Loops are crucial in batch data operations, simulation models, and real-time monitoring scripts in R—automating the logic for scalable data analysis.
FAQs – Loops in R
When should I use a for loop vs while loop in R?
Use for when the number of iterations is known; use while when it’s based on dynamic conditions.
What is the default loop exit strategy in repeat?
There is no default exit—you must include a break condition to stop the loop manually.
Can I loop through both keys and values in a list?
Yes, use names() or seq_along():
mylist <- list(a=10, b=20)
for (i in names(mylist)) {
print(paste(i, mylist[[i]]))
}
What happens if I forget the break in a repeat loop?
It creates an infinite loop and must be manually stopped (Esc or Stop in RStudio).
Is looping slow in R?
Native loops can be slower than vectorized functions. Prefer functions like apply(), lapply() for large datasets when possible.
Share Now :
