TExcelTAD
Home › R › R Lists

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.

r · try it yourself
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
r · try it yourself
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:

r · try it yourself
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

r · try it yourself
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:

r · try it yourself
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

r · try it yourself
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:

r · try it yourself
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"])?

  1. "integer"
  2. "list"
  3. "character"
  4. "vector"

How do you remove the element tmp from list l?

  1. l$tmp <- NA
  2. l$tmp <- NULL
  3. delete(l$tmp)
  4. rm(l$tmp)

Which function gives a compact overview of an object's structure?

  1. str()
  2. summary()
  3. print()
  4. cat()