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.
<- function(vecs = list(), ...) {
means <- length(vecs)
n if ( n == 0 ) {
return(cat("Need some vectors to work with!"))
}<- numeric()
results for ( vec in vecs ) {
print(vec)
<- c(results, mean(vec, ...))
results
}
results }
<- 1:5
vec1 <- 1:10
vec2 <- c(1:20, NA)
vec3 means(vecs = list(vec1, vec2, vec3), na.rm = TRUE)
## [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:
<- function(vecs = list(), ...) {
means2 <- length(vecs)
n if ( n == 0 ) {
return(cat("Need some vectors to work with!"))
}<- numeric(n)
results for ( i in 1:n ) {
<- mean(vecs[[i]], ...)
results[i]
}
results }
means2(vecs = list(vec1, vec2, vec3), na.rm = TRUE)
## [1] 3.0 5.5 10.5