Coding

For Loop in R: Syntax, seq_along, next and break Examples

A for loop in R repeats a statement once for each element of a vector or list: for (i in 1:3) print(i) runs three times with i set to 1, 2 and 3. The general form is for (var in seq) expr, and this page covers looping over vectors and lists, seq_along, next, break, preallocation and the loops that are not for.

For loop syntax in R

The R documentation gives the syntax as:

for (var in seq) expr

var is the loop variable, seq is a vector or list, and expr is the statement to run. In the R language definition's wording, for each element in the vector the variable name is set to the value of that element and the statement is evaluated. When the body is more than one statement, wrap it in curly braces:

for (i in 1:3) {
  print(i)
}

Example output:

[1] 1
[1] 2
[1] 3

There is no counter to increment and no end keyword. The opening brace goes on the same line as the for header by convention, and R only needs the braces when the body is more than one statement.

Loop over a vector of values

The sequence does not have to be numbers. Any vector works, and the loop variable takes each element in order:

fruits <- c("apple", "banana", "cherry")
for (f in fruits) {
  cat(f, "\n")
}

Example output:

apple
banana
cherry

This is usually the cleanest form when you need the values and not their positions. A range such as 1:10 and a vector you built yourself are handled the same way.

Loop over positions with seq_along

When you need the position as well, for example to write into the same slot of another vector, loop over the indices:

scores <- c(72, 85, 91)
names_list <- c("Ana", "Ben", "Cy")
for (i in seq_along(scores)) {
  cat(names_list[i], "scored", scores[i], "\n")
}

Example output:

Ana scored 72
Ben scored 85
Cy scored 91

seq_along(scores) returns 1, 2, 3. You may see 1:length(scores) in older code, and it gives the same result for a non-empty vector. The difference shows up with an empty one. Advanced R warns that 1:length(x) fails in unhelpful ways when x has length 0, because the : operator also counts down:

x <- c()
1:length(x)
seq_along(x)

Example output:

[1] 1 0
integer(0)

A loop over 1:length(x) would run twice, with i equal to 1 and then 0, on data that has no elements. A loop over seq_along(x) runs zero times. R's documentation confirms the second behaviour: if seq has length zero, the body of the loop is skipped. For the rows of a matrix or data frame, the same reasoning gives seq_len(nrow(m)).

Loop over a list

A list can hold different types, and the loop variable takes one element at a time:

items <- list(42, "text", TRUE)
for (item in items) {
  print(class(item))
}

Example output:

[1] "numeric"
[1] "character"
[1] "logical"

If you need the names of a named list too, loop over names(items) and index with items[[name]].

Skip with next, stop with break

Two statements change the normal flow. The R language definition says break causes an exit from the innermost loop that is currently being executed, and next immediately returns control to the start of the loop, which moves on to the following element.

for (n in 1:10) {
  if (n %% 2 == 0) next
  if (n > 7) break
  print(n)
}

Example output:

[1] 1
[1] 3
[1] 5
[1] 7

Even numbers are skipped by next. When n reaches 9, the odd number that passes the first test, break ends the loop before anything is printed. In nested loops, both statements only affect the loop they are written in, so a break in an inner loop does not stop the outer one.

Collect results: preallocate, then fill

A loop returns nothing useful, so results have to be stored in something you create beforehand. Advanced R recommends preallocating the output container, because growing one on every pass makes the loop slow. Use numeric(), character() or vector() with a length:

squares <- numeric(5)
for (i in seq_along(squares)) {
  squares[i] <- i^2
}
squares

Example output:

[1]  1  4  9 16 25

For a list of results of any type, vector("list", n) creates a list of length n. Advanced R uses out <- vector("list", length(means)) for this. The pattern to avoid is result <- c(result, new_value) inside the loop, which copies the whole vector each time.

Things a for loop does that surprise people

  • The loop returns NULL. The documentation states that for, while and repeat return NULL invisibly. Writing result <- for (i in 1:3) i leaves result as NULL.
  • The loop variable survives. The R language definition notes that the variable still exists after the loop and holds the last element. After for (i in 1:3) {}, typing i prints [1] 3. For a zero-length sequence, the documentation says the variable is set to NULL. Advanced R adds that the loop overwrites any existing variable with the same name, so pick a name you are not using elsewhere.
  • The sequence is evaluated once. Changing seq inside the loop has no effect on the iterations. If you append to the vector you are looping over, the loop still visits only the original elements.
  • Assigning to the loop variable does not carry over. You can assign to var inside the body, but the documentation says this will not affect the next iteration, which takes the next element of the original sequence.
  • Nothing prints by itself. At the console, typing x shows its value, but a bare x inside a loop body does not. Use print(x) or cat() to see values from inside a loop.
  • Dates lose their class. Advanced R notes that looping over an S3 vector such as dates strips the attributes. Loop over seq_along(xs) and use xs[[i]] to keep them.

While and repeat loops

When you do not know in advance how many passes you need, R has two other loops, listed in the same help page:

while (cond) expr
repeat expr

while checks its condition before each pass. repeat has no condition and runs until a break:

total <- 0
n <- 0
while (total < 10) {
  n <- n + 1
  total <- total + n
}
c(n, total)

Example output:

[1] 4 10

The loop adds 1, 2, 3 and 4 and stops when the total reaches 10. The same logic with repeat puts the test inside the body: repeat { ...; if (total >= 10) break }. Forgetting the break in a repeat loop gives an infinite loop, and in the console you stop it with Esc (RStudio) or Ctrl+C.

When not to write a loop

Many R operations are vectorised, so the loop is unnecessary. x^2 squares every element of x, and sum(x) adds them. For applying a function to each element and collecting the results, sapply(x, f) and lapply(x, f) return the results for you, so there is no output container to manage. A for loop is the right choice when each pass depends on the previous one, when the body has side effects such as writing a file, or when it reads more clearly than the alternative.

If you are comparing languages, loops in other languages are covered in Bash for loop examples.

Frequently asked questions

What is the syntax of a for loop in R?
The syntax is for (var in seq) expr. R sets var to each element of seq in turn and evaluates expr once per element. For more than one statement, wrap the body in curly braces: for (i in 1:3) { print(i) }.
Why should I use seq_along(x) instead of 1:length(x)?
If x has length 0, 1:length(x) becomes 1:0, which is the two values 1 and 0, so the loop body runs with an invalid index. seq_along(x) returns an empty integer vector for an empty x, so the body is skipped, which is almost always what you want.
Does a for loop return a value in R?
No. for, while and repeat return NULL invisibly, so you cannot assign a loop's result to a variable and get anything useful. Build the result inside the loop, in a vector or list you created before it.
How do I skip an iteration or stop a for loop in R?
Use next to skip the rest of the current iteration and move on to the following element. Use break to leave the innermost loop immediately. Both work in for, while and repeat loops.
Is a for loop slow in R?
A loop itself is fine. The usual slowdown is growing a result with c() or by indexing past its end on every pass. Create the result at full size first, for example with vector() or numeric(), and fill it in the loop.

Sources