Basics of R Lists 2015-05-25

It is common for new R users to be confused by R’s lists. This is particularly true for those who have been using a language where everything is treated as a matrix. Here are some basics of R lists. For a more advanced discussion, you can read the official documentation.

First, some motivation. What can you do with a list that you don’t do with other data structures?

Suppose you run a regression of consumption on income. If you only care about the coefficients, a vector with two elements, the estimated intercept and slope coefficient, will suffice. In practice, you want more than just the estimated coefficients. Depending on the situation, you will want the coefficients, the standard errors, the residuals, the data, the names of the variables, and other information. You cannot (reasonably) store all of that information in a matrix.

Lists comes in handy in this situation because it can hold objects of arbitrary types. An example list is

x <- list(a=1, b="Hello", c=rnorm(10))

The list x holds a scalar (a), a string (b), and a vector of ten pseudo-random numbers (c). The elements of x (called components) have been given names. This allows access by name or by index. In general, you should access the components by name, because it is easier to avoid bugs in the first place, and easier to find them when they do occur. To access by name, you can do

x[["a"]]
x[["b"]]
x[["c"]]

Note the use of double brackets. Alternatively, you can do

x$a
x$b
x$c

The names of list items can hold almost any symbol. It is perfectly acceptable to define a list like this:

z <- list("y_[t+1]"=5.7, "{Mom's birthday}"="April 24")

You have to use quotes if the name includes special characters. You can find your Mom’s birthday using

z[["{Mom's birthday}"]]
z$"{Mom's birthday}"

You need to use quotes with the dollar sign when there are special characters. You can set elements in the usual way. A convenient feature of lists is that the element will be added if it doesn’t already exist.

z[["y_[t+1]"]] <- 6.8
z[["{Dad's birthday}"]] <- "January 14"

The first line changes the value of y_[t+1]; the second creates a third component in z to hold your Dad’s birthday.


⤺ Back to the List of Computing Posts