R For Loop
A for loop runs a block of code once for each element of a vector or list. The loop variable takes each value in turn.
fruits <- c("apple", "banana", "cherry")
for (fruit in fruits) {
cat("I like", fruit, "\n")
}I like apple
I like banana
I like cherry
Looping over numbers
1:n creates the sequence 1, 2, …, n, and seq() gives more control:
for (i in 1:3) {
cat("Lap", i, "\n")
}
for (x in seq(0, 1, by = 0.25)) {
cat(x, "")
}
cat("\n")Lap 1
Lap 2
Lap 3
0 0.25 0.5 0.75 1
Looping over positions with seq_along()
When you need the index as well as the value, loop over seq_along(x). It is safer than 1:length(x), which goes wrong for an empty vector (1:0 is c(1, 0)):
cities <- c("Oslo", "Lima", "Pune")
for (i in seq_along(cities)) {
cat(i, ":", cities[i], "\n")
}
empty <- c()
1:length(empty)
seq_along(empty)1 : Oslo
2 : Lima
3 : Pune
[1] 1 0
integer(0)
Building a result
A common pattern is to create an empty vector of the right length, then fill it in the loop. Pre-allocating is much faster than growing the vector with c() each time:
n <- 8
fib <- numeric(n)
fib[1:2] <- 1
for (i in 3:n) {
fib[i] <- fib[i - 1] + fib[i - 2]
}
fib[1] 1 1 2 3 5 8 13 21
break and next
They work just like in while loops:
for (n in 1:20) {
if (n %% 3 != 0) next # skip numbers not divisible by 3
if (n > 12) break # stop after 12
cat(n, "")
}
cat("\n")3 6 9 12
Nested loops
A loop inside a loop runs the inner loop completely for each pass of the outer one:
for (row in 1:3) {
line <- ""
for (col in 1:4) {
line <- paste0(line, sprintf("%4d", row * col))
}
cat(line, "\n")
} 1 2 3 4
2 4 6 8
3 6 9 12
Do you need a loop?
Many loops in other languages are a single vectorised call in R. Loops are fine and sometimes clearer, but check for a vectorised version first:
| Loop version | Vectorised version |
|---|---|
| add each element to a total | sum(x) |
| square each element | x^2 |
| count elements over 10 | sum(x > 10) |
| apply a function to each element | sapply(x, f) (see the Apply Family lesson) |
Test yourself
What does for (x in c(2, 4, 6)) cat(x / 2, "") print?
- 2 4 6
- 1 2 3
- 6
- An error
Why is seq_along(x) safer than 1:length(x)?
- It is faster
- It returns an empty sequence for an empty x
- It starts at 0
- It sorts x
How many times does the inner cat() run in for (i in 1:3) for (j in 1:2) cat(i, j)?
- 3
- 5
- 6
- 2