Skip to content
AgileLogics
6 min read

Loops

Prerequisites: Conditionals

A loop repeats code. R has for, while, and repeat loops.

for loops

for (i in 1:3) {
  cat("Pass", i, "\n")
}

fruits <- c("apple", "banana", "cherry")
for (fruit in fruits) {
  cat("I like", fruit, "\n")
}
Pass 1
Pass 2
Pass 3
I like apple
I like banana
I like cherry

To loop over positions, use seq_along() — it's safe even for an empty vector, where 1:length(x) would wrongly give 1 0:

fruits <- c("apple", "banana")
for (i in seq_along(fruits)) {
  cat(i, ". ", fruits[i], "\n", sep = "")
}
1. apple
2. banana

while and repeat

balance <- 100
months <- 0
while (balance < 200) {
  balance <- balance * 1.1
  months <- months + 1
}
cat("Doubled after", months, "months\n")

n <- 1
repeat {
  n <- n * 2
  if (n >= 1000) break
}
n
Doubled after 8 months
[1] 1024

repeat loops forever until break. next skips to the next pass.

Often, you don't need a loop

Because R is vectorized, many loops can be replaced by a single expression — which is shorter and much faster:

prices <- c(10, 20, 30)

# Loop version
with_tax <- numeric(length(prices))
for (i in seq_along(prices)) {
  with_tax[i] <- prices[i] * 1.2
}
with_tax

# Vectorized version
prices * 1.2
[1] 12 24 36
[1] 12 24 36

When you do need a loop, create the result vector first at its full size (as numeric(length(prices)) does above), rather than growing it one element at a time, which is slow.

Common mistakes

  • Writing for (i in 1:length(x)) — breaks when x is empty. Use seq_along(x).
  • Writing a loop where a vectorized function already exists (sum, cumsum, ifelse, paste...).

Practice

Print the 5 times table from 5 x 1 = 5 to 5 x 10 = 50 — first with a loop, then with a single vectorized paste call.

Show solution
for (n in 1:10) {
  cat("5 x", n, "=", 5 * n, "\n")
}

paste("5 x", 1:10, "=", 5 * 1:10)