Learn R Programming  /  Control Flow  /  For Loop

For Loop

A for loop repeats a block of code once for every element in a sequence - the loop to reach for whenever you already know what you are iterating over.

Basic for Loop

R Code
for (i in 1:5) {
  print(i^2)
}
Output
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25

Looping Over a Vector

R Code
fruits <- c("apple", "banana", "mango")

for (fruit in fruits) {
  cat("I like", fruit, "\n")
}
Output
I like apple 
I like banana 
I like mango

Looping with an Index

Use seq_along() to get a safe index sequence - safer than 1:length(x), which misbehaves on an empty vector.

R Code
fruits <- c("apple", "banana", "mango")

for (i in seq_along(fruits)) {
  cat(i, ":", fruits[i], "\n")
}
Output
1 : apple 
2 : banana 
3 : mango
⚠ Common Mistake
1:length(x) looks equivalent to seq_along(x), but if x has zero elements, 1:length(x) becomes 1:0, which is c(1, 0) - not empty! This silently runs the loop body with a bad index. seq_along(x) correctly produces an empty sequence in that case.

break and next in a for Loop

R Code
for (i in 1:10) {
  if (i %% 2 == 0) next    # skip even numbers
  if (i > 7) break       # stop once i exceeds 7
  print(i)
}
Output
[1] 1
[1] 3
[1] 5
[1] 7

Advanced: Nested for Loops

🚀 Advanced Example
Nested loops are used to work through every combination of two sequences - here, building a small multiplication table.
R Code
for (i in 1:3) {
  for (j in 1:3) {
    cat(i, "x", j, "=", i*j, "  ")
  }
  cat("\n")
}
Output
1 x 1 = 1   1 x 2 = 2   1 x 3 = 3   
2 x 1 = 2   2 x 2 = 4   2 x 3 = 6   
3 x 1 = 3   3 x 2 = 6   3 x 3 = 9
💡 Tip
Before reaching for a for loop over a vector, ask whether a vectorised operation or sapply() could do the same job in one line - it is usually faster and more readable in R. Loops shine when each step depends on the result of the previous one, or when working with side effects like printing or file writing.

Key Points

  • for (item in sequence) repeats once per element - the sequence can be a vector, list, or range.
  • Use seq_along(x) instead of 1:length(x) to safely handle empty vectors.
  • break stops the loop entirely; next skips to the following iteration.
  • Prefer vectorised operations or apply functions over a for loop when performance and readability matter.