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.

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

means2 <- function(vecs = list(), ...) {
  n <- length(vecs)
  if ( n == 0 ) {
    return(cat("Need some vectors to work with!"))
  }
  results <- numeric(n)
  for ( i in 1:n ) {
    results[i] <- mean(vecs[[i]], ...)
  }
  results
}
means2(vecs = list(vec1, vec2, vec3), na.rm = TRUE)
## [1]  3.0  5.5 10.5