01 / 20

For Loops in
R Programming

Master iteration over sequences and indices using R's for loop: the foundational tool for repeating operations on data.

R Programming

What Is a For Loop?

A for loop is a control structure that tells R to repeat a block of code once for each element in a sequence. Instead of writing the same operation five times, you write it once and let the loop handle the repetition.

Why Use For Loops?

Reduce Repetition
Write code once instead of copying and pasting the same line dozens of times.
Process Data
Apply a calculation or transformation to every element in a vector or data frame.
Automate Tasks
Generate plots, read multiple files, or run simulations without manual effort.

Anatomy of a For Loop

for ( i in 1:5 ) { print ( i ) } Keyword Loop Variable Sequence Loop Body How it reads: "For each value i in the sequence 1 to 5, run the code inside the braces."

The Formal Syntax

for (variable in sequence) { # code to execute each iteration }
1
variable: a name you choose (like i, x, or name) that takes on each value.
2
sequence: any R vector, list, or range (e.g., 1:10, c("a","b","c")).
3
{ body }: the code block that runs once per element. Curly braces are required for multi-line bodies.

How a For Loop Flows

Start More elements in sequence? Yes Assign next value to i Execute loop body Loop back No End

Sequences vs. Indices

Loop Over Values Loop Over Indices
Syntax for (x in vec) for (i in 1:length(vec))
Variable holds Each element directly A position number
Access element x vec[i]
Best for Simple operations on each value When you need the position or modify in place

How to Write a For Loop

1
Identify the sequence: What collection of values do you need to iterate over? A vector, a range, column names?
2
Choose your loop variable name: Pick something descriptive: i for index, name for strings, val for values.
3
Write the body: What should happen to each element? Put that code inside the curly braces { }.
4
Pre-allocate if storing results: Create an output vector before the loop with numeric(length(seq)) or vector("list", n).
5
Test with a small sequence: Run with 2-3 elements first to verify correctness before scaling up.

Example 1: Looping Over Values

fruits <- c("apple", "banana", "cherry") for (fruit in fruits) { print(paste("I like", fruit)) }
[1] "I like apple" [1] "I like banana" [1] "I like cherry"

Example 2: Looping Over Indices

scores <- c(85, 92, 78, 95) curved <- numeric(length(scores)) for (i in seq_along(scores)) { curved[i] <- scores[i] + 5 } print(curved)
[1] 90 97 83 100

Example 3: Nested For Loops

# Multiplication table (3x3) for (row in 1:3) { line <- "" for (col in 1:3) { line <- paste(line, row * col) } print(line) }
[1] " 1 2 3" [1] " 2 4 6" [1] " 3 6 9"

Tracing a Loop Step by Step

Consider: for (i in 1:4) { result[i] <- i^2 }

Iteration i \( i^2 \) result
1st 1 1 c(1, _, _, _)
2nd 2 4 c(1, 4, _, _)
3rd 3 9 c(1, 4, 9, _)
4th 4 16 c(1, 4, 9, 16)

Accumulating Results

# Sum all values in a vector nums <- c(10, 20, 30, 40) total <- 0 for (val in nums) { total <- total + val } print(total)
[1] 100

break and next

break
Immediately exits the entire loop. No more iterations run. Use when you found what you need and want to stop early.
next
Skips the rest of the current iteration and jumps to the next one. The loop itself continues running.
for (i in 1:10) { if (i %% 2 == 0) next # skip even numbers if (i > 7) break # stop after 7 print(i) }
[1] 1 [1] 3 [1] 5 [1] 7

Common Mistakes

✕ Growing vectors in a loop
Using c(result, new_val) each iteration copies the entire vector. Pre-allocate with numeric(n) instead.
✕ Using 1:length(x) on empty vectors
If x has length 0, 1:0 gives c(1,0) and the loop runs twice with errors. Use seq_along(x) instead.
✕ Forgetting curly braces
Without { }, only the first line after for is inside the loop. Multi-line bodies always need braces.

Summary Reference

Pattern Code Template Use Case
Value loop for (x in vec) { ... } Print, filter, simple transforms
Index loop for (i in seq_along(vec)) { ... } Modify in place, access position
Accumulator total <- 0; for (...) total <- total + x Sums, counts, concatenation
Nested loop for (i in ...) { for (j in ...) { } } Matrices, combinations, grids
Early exit if (cond) break / next Search, skip invalid data

Question 1 of 5

What will the following code print?
for (x in c(2, 4, 6)) { print(x * 10) }

Question 2 of 5

Which function is safer than 1:length(vec) for generating loop indices, especially when vec might be empty?

Question 3 of 5

What does the next keyword do inside a for loop?

Question 4 of 5

You want to store the square of each number from 1 to 100. Which approach is most efficient?

Question 5 of 5

What is the value of count after this code runs?