Lists
By the end of this tutorial, you will be able to:
- Describe the characteristics of an R list.
- Describe important use-cases for lists, and explain why lists are the best choice in these situations.
- Create new lists in R.
- Access and modify list elements using different methods, and explain the difference between the available selection operators (
$,[],[[]]).
Lists are one of R’s most versatile and ubiquitous data structures. Like vectors, lists are one-dimensional objects. Unlike vectors, however, lists can comprise arbitrary mixes of data objects with any combination of types. This flexibility makes lists particularly useful for storing and organizing heterogeneous data such as the results returned from statistical modeling functions. Understanding why you’d use a list instead of a vector (not just how to create lists) is one of the main goals of this tutorial.
Why Use Lists?
There are a few common situations where a list is the natural (or only) choice:
Storing mixed-type information about one thing
If you want to store someone’s name (character), age (numeric), and active status (logical) in a single object, you can’t use a vector (or matrix). A vector would coerce each piece of data into one shared type. A list stores each piece with its original type.
Storing the results of a complex function
Many R functions (especially statistical modeling functions) return several pieces of output (e.g., coefficients, fitted values, diagnostic statistics, transformed data), all with different shapes and types. A list is the only structure flexible enough to hold all of these disparate elements in one object.
You’ll see the second data structure in the next tutorial, the data frame, is actually a special, constrained kind of list. So getting comfortable with lists now will make data frames feel much less mysterious later.
In your own words, explain why a list would work better than a vector if you wanted to store the result of a logical comparison and the result of an arithmetic calculation in one object.