Lists
Prerequisites: Vectors, Functions
A vector holds values of one type. A list can hold anything — numbers, text, vectors, even other lists — each element of any type and length.
Real-world analogy: a vector is an egg carton (every slot holds an egg); a list is a toolbox, with compartments holding whatever you like.
Creating lists
person <- list(name = "Ada", age = 36, languages = c("R", "Python"))
person
$name
[1] "Ada"
$age
[1] 36
$languages
[1] "R" "Python"
Accessing elements
person <- list(name = "Ada", age = 36, languages = c("R", "Python"))
person$name
person[["age"]]
person$languages[2]
length(person)
names(person)
[1] "Ada"
[1] 36
[1] "Python"
[1] 3
[1] "name" "age" "languages"
$nameand[["name"]]get an element's contents.- Single brackets,
person["name"], return a smaller list containing that element — a common source of confusion.
Analogy: if a list is a train, [ ] gives you a shorter train with
some of the carriages; [[ ]] gives you what's inside one carriage.
Changing lists
person <- list(name = "Ada", age = 36)
person$age <- 37
person$email <- "ada@example.com"
person$name <- NULL
str(person)
List of 2
$ age : num 37
$ email: chr "ada@example.com"
- Assigning to a new name adds an element.
- Assigning
NULLremoves one. str()shows a compact overview of any object's structure — invaluable for exploring data.
Many R functions return lists — for example, statistical tests and models — and JSON data read into R becomes lists.
Common mistakes
- Using
[ ]when you meant[[ ]], then being surprised that arithmetic fails on the result. - Typos in names:
person$nmaequietly returnsNULLrather than an error.