For Loops in
R Programming
Master iteration over sequences and indices using R's for loop: the foundational tool for repeating operations on data.
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?
Anatomy of a For Loop
The Formal Syntax
How a For Loop Flows
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
Example 1: Looping Over Values
Example 2: Looping Over Indices
Example 3: Nested For Loops
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
break and next
Common Mistakes
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?
Code:
count <- 0
for (i in 1:10) {
if (i %% 3 == 0) {
count <- count + 1
}
}