Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 39 ยท Control Flow and Functions

Loops in R: for, while and repeat

Learn R loops: for, while and repeat with break and next, why seq_along() beats 1:length(x), how to preallocate results, and when vectorized code replaces a loop.

A loop repeats a block of code. You use loops to process each file in a folder, to retry something until it works, or to simulate a process step by step. R has three loop forms: for (repeat for each item), while (repeat as long as a condition holds) and repeat (repeat until you say break).

R programmers also learn when not to loop. Because most operations are vectorized, many jobs that need a loop in other languages are a single expression in R. This lesson covers both sides.

for loops

R
for (i in 1:3) {
  print(i^2)
}
#> [1] 1
#> [1] 4
#> [1] 9

The loop variable (i) takes each value of the sequence in turn, and the body runs once per value. The sequence can be any vector, including text:

R
fruits <- c("apple", "pear", "plum")

for (fruit in fruits) {
  cat("I like", fruit, "\n")
}
#> I like apple 
#> I like pear 
#> I like plum 

Output inside loops needs print() or cat() explicitly. R prints results automatically only for expressions typed at the top level, not for values computed inside a loop body.

Looping by position with seq_along()

Often you need the index as well as the value:

R
for (i in seq_along(fruits)) {
  cat(i, ":", fruits[i], "\n")
}
#> 1 : apple 
#> 2 : pear 
#> 3 : plum 

seq_along(x) gives 1, 2, ..., length(x). Prefer it over 1:length(x). The reason is the empty vector:

R
x <- c()
1:length(x)
#> [1] 1 0

seq_along(x)
#> integer(0)

1:0 counts down to c(1, 0), so a loop over an empty vector would wrongly run twice. seq_along() and seq_len(n) return nothing, so the loop body is correctly skipped.

Building results: preallocate

A loop usually produces a result. The safe, fast pattern is to create an empty container of the final size first, then fill it:

R
squares <- numeric(5)        # five zeros

for (i in 1:5) {
  squares[i] <- i^2
}
squares
#> [1]  1  4  9 16 25

Growing a vector inside the loop (result <- c(result, new)) works but copies the whole vector each time and becomes very slow for large data. numeric(n), character(n), logical(n) and vector("list", n) create the right container.

while loops

while checks a condition before each pass:

R
n <- 1
while (n < 100) {
  n <- n * 2
}
n
#> [1] 128

Make sure something inside the loop changes the condition, or it runs forever. (In RStudio press the red Stop button; in a plain console press Ctrl+C.)

A classic example is the Collatz sequence: if the number is even halve it, otherwise multiply by three and add one. It always seems to reach 1:

R
n <- 6
steps <- n

while (n != 1) {
  if (n %% 2 == 0) {
    n <- n / 2
  } else {
    n <- 3 * n + 1
  }
  steps <- c(steps, n)
}
steps
#> [1]  6  3 10  5 16  8  4  2  1

The same algorithm in Python, as a runnable comparison, shows that the loop logic transfers directly between languages:

Python Comparison: the Collatz loop in Python

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

repeat, break and next

repeat loops forever until break stops it. That suits "keep trying until it works" logic:

R
count <- 0
repeat {
  count <- count + 1
  if (count == 3) break
}
count
#> [1] 3

Two keywords control any loop:

  • break leaves the loop immediately.
  • next skips the rest of the current pass and moves to the next value.
R
for (i in 1:6) {
  if (i %% 2 == 0) next       # skip even numbers
  cat(i, "")
}
cat("\n")
#> 1 3 5 
flowchart TD
    A["Next value?"] -->|no| Z["Loop ends"]
    A -->|yes| B{"next?"}
    B -->|yes| A
    B -->|no| C["Run body"]
    C --> D{"break?"}
    D -->|yes| Z
    D -->|no| A

Figure: how next and break steer a loop.

Do you need a loop at all?

A vectorized expression is shorter and usually much faster:

R
x <- 1:5

# Loop version
total <- 0
for (v in x) total <- total + v^2
total
#> [1] 55

# Vectorized version
sum(x^2)
#> [1] 55

Use a loop when each step depends on the previous result (like the Collatz example), when you perform side effects such as writing files, or when the logic is complicated. For the common job "apply a function to each element", the apply family is clearer than a loop and avoids index bookkeeping.

Looping over data frame rows and lists

A data frame is a list of columns, so for (col in df) loops over columns. To go through rows by position, use seq_len(nrow(df)):

R
for (i in seq_len(nrow(mtcars[1:3, ]))) {
  cat(rownames(mtcars)[i], "has", mtcars$cyl[i], "cylinders\n")
}
#> Mazda RX4 has 6 cylinders
#> Mazda RX4 Wag has 6 cylinders
#> Datsun 710 has 4 cylinders

Row-by-row loops over large tables are slow; prefer column operations or dplyr.

Common mistakes

  1. Using 1:length(x) on possibly empty input; use seq_along(x).
  2. Growing a vector inside a loop instead of preallocating.
  3. A while condition that never becomes false.
  4. Expecting auto-printing inside the body; call print() or cat().
  5. Changing the vector you are looping over; the loop uses the original values.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does 1:length(x) produce when x is an empty vector?

    1:0 counts downwards to c(1, 0). Use seq_along(x) to get an empty sequence.
  2. 2. What does next do inside a loop?

    next jumps to the following iteration; break ends the loop.
  3. 3. Why preallocate a result vector before a loop?

    numeric(n) creates the final size once; then you fill it with result[i] <- ...
  4. 4. Which loop checks its condition before every pass?

    while tests first, so it may run zero times. repeat has no condition and relies on break.

Summary

  • for repeats over a sequence, while repeats while a condition is true, repeat loops until break.
  • Use seq_along(x) and seq_len(n) instead of 1:length(x).
  • Preallocate results with numeric(n) or vector("list", n).
  • break exits the loop; next skips to the next iteration.
  • Prefer vectorized code or the apply family when you can; loop when steps depend on each other.

Next: Functions