Previous: Ways to create arrays Up: Data Structures Next: Data Frames

Lists

Unlike arrays, which contain only one type of scalar value, lists are flexible data structures that can contain heterogeneous value types and heterogeneous data structures. Lists are so flexible that one list can contain another list. For example, the list output can contain coef, a vector of regression coefficients; variance, the variance-covariance matrix; and another list terms that describes the data using character strings. Use the names() function to view the named elements in a list, and to extract a named element, use

> names(output)
 [1] coefficients   variance   terms
> output$coefficients
For lists where the elements are not named, use double square brackets [[ ]] to extract elements:
> L[[4]]      # Extracts the 4th element from the list `L'
> L[[4]] <- b # Replaces the 4th element of the list `L' with a matrix `b'

Like vectors, lists are flexible data structures that can be extended without first creating another list of with the correct number of elements:

> L <- list()                      # Creates an empty list
> L$coefficients <- c(1, 4, 6, 8)  # Inserts a vector into the list, and 
                                   #  names that vector `coefficients' 
				   #  within the list
> L[[4]] <- c(1, 4, 6, 8)          # Inserts the vector into the 4th position
                                   #  in the list.  If this list doesn't 
                                   #  already have 4 elements, the empty 
                                   #  elements will be `NULL' values
Alternatively, you can easily create a list using objects that already exist in your workspace:
> L <- list(coefficients = k, variance = v) # Where `k' is a vector and
                                            #   `v' is a matrix



Gary King 2011-11-29