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:
100
i <-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 entirefor
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.
c(1, 50, 20)
means <- vector("list", length(means))
out <-for (i in 1:length(means)) {
rnorm(10, means[[i]])
out[[i]] <- }
Next, beware of iterating over 1:length(x)
, which will fail in unhelpful ways if x
has length 0:
c()
means <- vector("list", length(means))
out <-for (i in 1:length(means)) {
rnorm(10, means[[i]])
out[[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)
vector("list", length(means))
out <-for (i in seq_along(means)) {
rnorm(10, means[[i]])
out[[i]] <- }
Finally, you might encounter problems when iterating over S3 vectors, as loops typically strip the attributes:
as.Date(c("2020-01-01", "2010-01-01"))
xs <-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
: performsaction
whilecondition
isTRUE
.repeat(action)
: repeatsaction
forever (i.e. until it encountersbreak
).
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
Why does this code succeed without errors or warnings?
numeric() x <- vector("list", length(x)) out <-for (i in 1:length(x)) { x[i] ^ 2 out[i] <- } out
When the following code is evaluated, what can you say about the vector being iterated?
c(1, 2, 3) xs <-for (x in xs) { c(xs, x * 2) xs <- } xs#> [1] 1 2 3 2 4 6
What does the following code tell you about when the index is updated?
for (i in 1:3) { i * 2 i <-print(i) }#> [1] 2 #> [1] 4 #> [1] 6