9.5 Iterating Over a List

Lists are one-dimensional, so you can loop over them just as you would loop over a atomic vector. Sometimes this can be quite useful.

Here is a toy example. We will write a function that, when given a list of vectors, will return a vector consisting of the means of each of the vectors in the list.

## [1] 1 2 3 4 5
##  [1]  1  2  3  4  5  6  7  8  9 10
##  [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 NA
## [1]  3.0  5.5 10.5

Another possibility—and one that will work a bit more quickly—is to iterate over the indices of the list of vectors:

## [1]  3.0  5.5 10.5