R For Loop

A for loop repeats a block of code once for each item in a sequence. Instead of writing the same code ten times, you write it once and tell R to run it ten times — once for each value in a list or range.

Syntax

for (variable in sequence) {
  # code to repeat
}

How the For Loop Works

Sequence: 1, 2, 3, 4, 5
           │  │  │  │  │
           ▼  ▼  ▼  ▼  ▼
  Loop runs 5 times
  Each time, "variable" holds the current value

Iteration 1: variable = 1 → run code
Iteration 2: variable = 2 → run code
Iteration 3: variable = 3 → run code
...
Iteration 5: variable = 5 → run code → STOP

Basic Example

for (i in 1:5) {
  cat("Iteration:", i, "\n")
}

Output:

Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5

Looping Over a Vector

fruits <- c("Apple", "Mango", "Banana", "Grape")

for (fruit in fruits) {
  cat("I like", fruit, "\n")
}

Output:

I like Apple
I like Mango
I like Banana
I like Grape

Using the Index to Access Elements

scores <- c(85, 92, 78, 95, 60)

for (i in 1:length(scores)) {
  cat("Student", i, "scored:", scores[i], "\n")
}

Output:

Student 1 scored: 85
Student 2 scored: 92
Student 3 scored: 78
Student 4 scored: 95
Student 5 scored: 60

Building Results Inside a Loop

# Calculate cumulative sum
numbers <- c(10, 20, 30, 40, 50)
running_total <- 0

for (n in numbers) {
  running_total <- running_total + n
  cat("Added", n, "| Total so far:", running_total, "\n")
}

Output:

Added 10 | Total so far: 10
Added 20 | Total so far: 30
Added 30 | Total so far: 60
Added 40 | Total so far: 100
Added 50 | Total so far: 150

Nested For Loops

# Multiplication table (3×3)
for (i in 1:3) {
  for (j in 1:3) {
    cat(i * j, "\t")
  }
  cat("\n")
}

Output:

1   2   3
2   4   6
3   6   9

Seq_along() — Safer Indexing

items <- c("pen", "book", "ruler")

for (i in seq_along(items)) {
  cat("Item", i, ":", items[i], "\n")
}

Use seq_along() instead of 1:length() — it handles empty vectors safely without causing errors.

When to Avoid For Loops in R

R is optimized for vectorized operations. Many tasks people solve with loops run much faster without them:

# Slow (loop)
x <- 1:1000000
result <- numeric(length(x))
for (i in seq_along(x)) result[i] <- x[i] * 2

# Fast (vectorized — no loop needed)
result <- x * 2

Use loops when you need sequential processing, building results step by step, or when the next iteration depends on the previous one. Use vectorized operations for applying the same calculation to every element independently.

Leave a Comment

Your email address will not be published. Required fields are marked *