R Lists
A vector holds values of one type. A list can hold anything: numbers, strings, vectors, data frames, functions, and even other lists. Lists are how R represents records, nested data and the results of most statistical functions.
person <- list(name = "Lina", age = 31, languages = c("R", "SQL", "Python"))
person
length(person)$name
[1] "Lina"
$age
[1] 31
$languages
[1] "R" "SQL" "Python"
[1] 3
Accessing elements
There are three ways in, and the difference matters:
| Syntax | Returns |
|---|---|
lst[[1]] or lst[["name"]] |
the element itself |
lst$name |
the element itself (shortcut for [["name"]]) |
lst[1] or lst["name"] |
a smaller list containing that element |
person <- list(name = "Lina", age = 31, languages = c("R", "SQL", "Python"))
person$name
person[["age"]]
person$languages[2]
class(person["age"])
class(person[["age"]])[1] "Lina"
[1] 31
[1] "SQL"
[1] "list"
[1] "numeric"
Think of a list as a train: [ ] gives you a shorter train, [[ ]] gives you the cargo of one carriage.
Changing, adding and removing
Assign to an element to change or add it; assign NULL to remove it:
config <- list(debug = FALSE, retries = 3)
config$retries <- 5
config$timeout <- 30
config$debug <- NULL
names(config)
str(config)[1] "retries" "timeout"
List of 2
$ retries: num 5
$ timeout: num 30
str() ("structure") gives a compact, one-line-per-element overview of any object. It is one of the most useful functions for exploring data.
Looping over a list
inventory <- list(apples = 12, pears = 0, plums = 7)
for (fruit in names(inventory)) {
cat(fruit, ":", inventory[[fruit]], "\n")
}
"pears" %in% names(inventory)apples : 12
pears : 0
plums : 7
[1] TRUE
Nested lists
Lists can contain lists, which models hierarchical data such as JSON:
shop <- list(
name = "Corner Café",
menu = list(
coffee = list(price = 2.8, sizes = c("S", "M", "L")),
tea = list(price = 2.2, sizes = c("M"))
)
)
shop$menu$coffee$price
shop[["menu"]][["tea"]][["sizes"]]
names(shop$menu)[1] 2.8
[1] "M"
[1] "coffee" "tea"
Joining lists and converting
a <- list(x = 1, y = 2)
b <- list(z = 3)
combined <- c(a, b)
names(combined)
unlist(combined) # flatten to a named vector
as.list(1:3)[[2]][1] "x" "y" "z"
x y z
1 2 3
[1] 2
unlist() flattens a list into a vector (coercing to a common type if needed), which is handy once every element is a single value.
Applying a function to each element
lapply() calls a function on every element and returns a list; sapply() simplifies the result to a vector when it can. The Apply Family lesson covers them in detail:
scores <- list(math = c(80, 92, 75), art = c(60, 88), music = c(95, 91, 99, 70))
sapply(scores, mean)
lapply(scores, length)$music math art music
82.33333 74.00000 88.75000
[1] 4
Test yourself
If l <- list(a = 1:3), what is class(l["a"])?
- "integer"
- "list"
- "character"
- "vector"
How do you remove the element tmp from list l?
- l$tmp <- NA
- l$tmp <- NULL
- delete(l$tmp)
- rm(l$tmp)
Which function gives a compact overview of an object's structure?
- str()
- summary()
- print()
- cat()