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:
<- list(name = "Dorothy", age = 12)
lst1 <- data.frame(x = c(10, 20, 30), y = letters[1:3])
df <- list(vowels = c("a", "e", "i", "o", "u"),
lst2 myFrame = df)
<- list(nums = 10:20,
lst3 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:
lst1
## $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:
$age lst1
## [1] 12
You can make an empty list, too:
<- list() emptyList
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
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 bewizard
.
- The sequence of even numbers from 4 to 100. Its name should be
Suppose that
ozStuff
has been created in the previous problem. Describe in your own words what the following expression does:<- c(ozStuff, list(dorothy = "Kansas")) ozStuff
9.1.2 Solutions to the Practice Exercises
Here’s one way to do it:
<- list(lion = seq(4, 100, by = 2), ozStuff scarecrow = LETTERS, wizard = bcscr::fuel)
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 calleddorothy
(which is the string"Kansas"
), and then binds the name “ozStuff
” to that new four-element list.