5.3 Loops

for loops are used to iterate over items in a vector. They have the following basic form:

for (item in vector) perform_action

For each item in vector, perform_action is called once; updating the value of item each time.

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

(When iterating over a vector of indices, it’s conventional to use very short variable names like i, j, or k.)

N.B.: for assigns the item to the current environment, overwriting any existing variable with the same name:

i <- 100
for (i in 1:3) {}
i
#> [1] 3

There are two ways to terminate a for loop early:

  • next exits the current iteration.
  • break exits the entire for loop.
for (i in 1:10) {
  if (i < 3) 
    next

  print(i)
  
  if (i >= 5)
    break
}
#> [1] 3
#> [1] 4
#> [1] 5

5.3.1 Common pitfalls

There are three common pitfalls to watch out for when using for. First, if you’re generating data, make sure to preallocate the output container. Otherwise the loop will be very slow; see Sections 23.2.2 and 24.6 for more details. The vector() function is helpful here.

means <- c(1, 50, 20)
out <- vector("list", length(means))
for (i in 1:length(means)) {
  out[[i]] <- rnorm(10, means[[i]])
}

Next, beware of iterating over 1:length(x), which will fail in unhelpful ways if x has length 0:

means <- c()
out <- vector("list", length(means))
for (i in 1:length(means)) {
  out[[i]] <- rnorm(10, means[[i]])
}
#> Error in rnorm(10, means[[i]]): invalid arguments

This occurs because : works with both increasing and decreasing sequences:

1:length(means)
#> [1] 1 0

Use seq_along(x) instead. It always returns a value the same length as x:

seq_along(means)
#> integer(0)

out <- vector("list", length(means))
for (i in seq_along(means)) {
  out[[i]] <- rnorm(10, means[[i]])
}

Finally, you might encounter problems when iterating over S3 vectors, as loops typically strip the attributes:

xs <- as.Date(c("2020-01-01", "2010-01-01"))
for (x in xs) {
  print(x)
}
#> [1] 18262
#> [1] 14610

Work around this by calling [[ yourself:

for (i in seq_along(xs)) {
  print(xs[[i]])
}
#> [1] "2020-01-01"
#> [1] "2010-01-01"

5.3.2 Related tools

for loops are useful if you know in advance the set of values that you want to iterate over. If you don’t know, there are two related tools with more flexible specifications:

  • while(condition) action: performs action while condition is TRUE.

  • repeat(action): repeats action forever (i.e. until it encounters break).

R does not have an equivalent to the do {action} while (condition) syntax found in other languages.

You can rewrite any for loop to use while instead, and you can rewrite any while loop to use repeat, but the converses are not true. That means while is more flexible than for, and repeat is more flexible than while. It’s good practice, however, to use the least-flexible solution to a problem, so you should use for wherever possible.

Generally speaking you shouldn’t need to use for loops for data analysis tasks, as map() and apply() already provide less flexible solutions to most problems. You’ll learn more in Chapter 9.

5.3.3 Exercises

  1. Why does this code succeed without errors or warnings?

    x <- numeric()
    out <- vector("list", length(x))
    for (i in 1:length(x)) {
      out[i] <- x[i] ^ 2
    }
    out
  2. When the following code is evaluated, what can you say about the vector being iterated?

    xs <- c(1, 2, 3)
    for (x in xs) {
      xs <- c(xs, x * 2)
    }
    xs
    #> [1] 1 2 3 2 4 6
  3. What does the following code tell you about when the index is updated?

    for (i in 1:3) {
      i <- i * 2
      print(i) 
    }
    #> [1] 2
    #> [1] 4
    #> [1] 6