R Language Lists Quick Introduction to Lists


In general, most of the objects you would interact with as a user would tend to be a vector; e.g numeric vector, logical vector. These objects can only take in a single type of variable (a numeric vector can only have numbers inside it).

A list would be able to store any type variable in it, making it to the generic object that can store any type of variables we would need.

Example of initializing a list

exampleList1 <- list('a', 'b')
exampleList2 <- list(1, 2)
exampleList3 <- list('a', 1, 2)

In order to understand the data that was defined in the list, we can use the str function.


Subsetting of lists distinguishes between extracting a slice of the list, i.e. obtaining a list containing a subset of the elements in the original list, and extracting a single element. Using the [ operator commonly used for vectors produces a new list.

# Returns List

To obtain a single element use [[ instead.

# Returns Character

List entries may be named:

exampleList4 <- list(
    num = 1:3,
    numeric = 0.5,
    char = c('a', 'b')

The entries in named lists can be accessed by their name instead of their index.


Alternatively the $ operator can be used to access named elements.


This has the advantage that it is faster to type and may be easier to read but it is important to be aware of a potential pitfall. The $ operator uses partial matching to identify matching list elements and may produce unexpected results.

exampleList5 <- exampleList4[2:3]

# c(1, 2, 3)

# 0.5


Lists can be particularly useful because they can store objects of different lengths and of various classes.

## Numeric vector
exampleVector1 <- c(12, 13, 14)
## Character vector
exampleVector2 <- c("a", "b", "c", "d", "e", "f")
## Matrix
exampleMatrix1 <- matrix(rnorm(4), ncol = 2, nrow = 2)
## List
exampleList3 <- list('a', 1, 2)

exampleList6 <- list(
    num = exampleVector1, 
    char = exampleVector2,
    mat = exampleMatrix1, 
    list = exampleList3
#[1] 12 13 14
#[1] "a" "b" "c" "d" "e" "f"
#          [,1]        [,2]
#[1,] 0.5013050 -1.88801542
#[2,] 0.4295266  0.09751379
#[1] "a"
#[1] 1
#[1] 2