Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 39 ยท Data Types and Structures

Lists in R

Learn R lists, the flexible container for mixed types. Create named lists, use $, [ ] and [[ ]] correctly, add and remove items, nest lists and flatten with unlist().

A vector holds values of one type. A list holds anything: numbers, text, other vectors, matrices, even functions and other lists, all side by side. If a vector is a row of identical boxes, a list is a drawer with compartments of different shapes. Lists are what R uses to return several results from one function, to represent records, and to hold JSON-like data. A data frame, which you will meet in Data Frames, is actually a list of equal-length vectors.

Creating lists

R
person <- list(
  name  = "Ada",
  age   = 36,
  langs = c("R", "Python")
)

length(person)
#> [1] 3

names(person)
#> [1] "name"  "age"   "langs"

Elements may have names, as here, or none: list(1, "a", TRUE). Names make a list act like a lookup record.

str() is the best way to inspect a list:

R
str(person)
#> List of 3
#>  $ name : chr "Ada"
#>  $ age  : num 36
#>  $ langs: chr [1:2] "R" "Python"

Three ways to access elements

This is the part that trips people up. There are three tools and each does something different.

Syntax Returns Example
person$name The element itself "Ada"
person[["name"]] The element itself "Ada"
person["name"] A smaller list list(name = "Ada")
R
person$name
#> [1] "Ada"

person[["age"]]
#> [1] 36

person["age"]
#> $age
#> [1] 36

Think of a list as a train of carriages. person["age"] hands you the carriage with the passenger in it (still a list). person[["age"]] hands you the passenger. When you want the value to compute with, use $ or [[.

Position works too: person[[1]] is the first element. To go deeper, chain the accessors:

R
person$langs[2]
#> [1] "Python"

person[["langs"]][1]
#> [1] "R"

Use [[ ]] with a variable holding the name (key <- "age"; person[[key]]), because $ takes the name literally.

Rule of thumb: [ ] keeps the container (list in, list out). [[ ]] and $ take one thing out of the container.

Adding, changing and removing

R
person$city <- "London"        # add
person$age  <- 37              # change
person$langs <- NULL           # remove (assign NULL)

names(person)
#> [1] "name" "age"  "city"

Assigning NULL deletes the element. To store an actual NULL value you must use person["x"] <- list(NULL), an edge case you rarely need.

Combine lists with c():

R
extra <- list(country = "UK")
person <- c(person, extra)
length(person)
#> [1] 4

Lists inside lists

Elements can be lists, so you can model nested data such as a customer with an address and several orders:

R
customer <- list(
  name = "Mira",
  address = list(city = "Oslo", zip = "0150"),
  orders = list(
    list(id = 1, total = 25.5),
    list(id = 2, total = 40)
  )
)

customer$address$city
#> [1] "Oslo"

customer$orders[[2]]$total
#> [1] 40

Read the second line from left to right: take orders, then its second element, then total. Data from web services (JSON) arrives in exactly this shape, which is why lists matter for working with APIs.

Looping over a list

Use lapply() to apply a function to each element and get a list back, or sapply() to simplify the result to a vector when possible:

R
scores <- list(math = c(80, 90), art = c(70, 85, 100), music = 60)

sapply(scores, length)
#>  math   art music 
#>     2     3     1 

sapply(scores, mean)
#>  math   art music 
#>  85.0  85.0  60.0 

These are explained fully in The apply Family. They work well here because the elements have different lengths, which a matrix could not store.

Flattening with unlist()

unlist() collapses a list into a vector, coercing to the most general type:

R
unlist(list(a = 1, b = 2, c = 3))
#> a b c 
#> 1 2 3 

unlist(list(1, "x", TRUE))
#> [1] "1"    "x"    "TRUE"

Comparing the structures

Structure Dimensions Types Typical use
Vector 1 One A column of numbers or words
Matrix 2 One Numeric grid
Array n One Multi-way numeric data
List 1 Any, mixed Records, nested data, function results
Data frame 2 One per column The standard table for analysis

Picking elements from a list

x$name The element itself
x[[1]] The element itself, by position
x[1] A list holding the element

Single bracket keeps the container.

1 / 2

Common mistakes

  1. Using x["name"] and then trying to do arithmetic on the result. It is still a list; use x[["name"]].
  2. Forgetting that x$name <- NULL deletes the element.
  3. Using c() when you wanted to nest: c(list(1), list(2)) joins, while list(list(1), list(2)) nests.
  4. Misspelling names. person$nme quietly returns NULL, not an error.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between x["a"] and x[["a"]]?

    Single brackets keep the list container, double brackets extract the content.
  2. 2. How do you delete the element age from the list p?

    Assigning NULL removes the element. Assigning NA only sets it to missing.
  3. 3. Given x <- list(a = list(b = 5)), how do you reach the 5?

    Chain the accessors from the outside in.
  4. 4. What does unlist(list(1, "x", TRUE)) return?

    unlist flattens and coerces to the most general type, which is character here.

Summary

  • A list holds elements of any type, including other lists, and can be named.
  • $ and [[ ]] extract an element; [ ] returns a smaller list.
  • Add or change with assignment; delete with <- NULL.
  • Nested lists model records and JSON-like data; chain $ and [[ ]] to dig in.
  • lapply(), sapply() and unlist() work with whole lists.

Next: Conditionals: if, else and ifelse