9.1 Introduction to Lists

So far the vectors that we have met have all been atomic, meaning that they can hold only one type of value. Hence we deal with vectors of type integer, or of type double, or of type character, and so on.

A list is a special kind of vector. Like any other vector it is one-dimensional, but unlike an atomic vector it can contain objects of any sort: atomic vectors, functions—even other lists! We say, therefore, that lists are heterogeneous vectors.

The most direct way to create a list is with the function list() . Let’s make a couple of lists:

lst1 <- list(name = "Dorothy", age = 12)
df <- data.frame(x = c(10, 20, 30), y = letters[1:3])
lst2 <- list(vowels = c("a", "e", "i", "o", "u"),
             myFrame = df)
lst3 <- list(nums = 10:20,
             bools = c(T, F, F),
             george = lst1)

Note that the elements of our three lists are not objects of a single data type. Note also that lst3 actually contains lst1 as one of its elements.

When you call list() to create a list, you have the option to assign a name to one or more of the elements. In the code above we chose, for both of our lists, to assign a name to each element.

Let’s print out a list to the console. We’ll choose lst1, since it’s rather small:

## $name
## [1] "Dorothy"
## $age
## [1] 12

Note that the name of each elements appears before the element itself is printed out, and that the names are preceded by dollar signs. This is a hint that you can access a single member of the list in a way similar to the frame$variable format for data frames:

## [1] 12

You can make an empty list, too:

emptyList <- list()

This is useful when you want to build up a list gradually, but you do not yet know what will go into it.

9.1.1 Practice Exercises

  1. Make a list called ozStuff. The list should contain three elements:

    • The sequence of even numbers from 4 to 100. Its name should be lion.
    • The uppercase letters of the alphabet. Its name should be scarecrow.
    • The data frame alcohol from the fuel package. Its name should be wizard.
  2. Suppose that ozStuff has been created in the previous problem. Describe in your own words what the following expression does:

    ozStuff <- c(ozStuff, list(dorothy = "Kansas"))

9.1.2 Solutions to the Practice Exercises

  1. Here’s one way to do it:

    ozStuff <- list(lion = seq(4, 100, by = 2),
                    scarecrow = LETTERS,
                    wizard = bcscr::fuel)
  2. One way to describe it is as follows: the expression creates a new list consisting of all the elements of ozStuff together with a new element called dorothy (which is the string "Kansas"), and then binds the name “ozStuff” to that new four-element list.