list()
Lists are the most flexible data structure in R. Unlike vectors, which must contain elements of the same type, lists can hold objects of different types, different lengths, and even other lists or functions. This makes lists ideal for storing complex, hierarchical data and returning multiple values from functions.
Creating Lists
Create a list using the list() function:
# A simple list with different types
my_list <- list(
name = "Alice",
age = 30,
scores = c(85, 92, 78),
active = TRUE
)
# Accessing elements
my_list[[1]] # "Alice" (by index)
my_list$name # "Alice" (by name)
my_list[["age"]] # 30 (by name with brackets)
List Structure and Inspection
Lists have a recursive nature — they can contain other lists:
# Nested list
nested <- list(
a = 1:3,
b = list(
c = c("x", "y"),
d = matrix(1:4, nrow = 2)
)
)
# Check structure
str(nested)
# List of 2
# $ a: int [1:3] 1 2 3
# $ b:List of 2
# ..$ c: chr [1:2] "x" "y"
# ..$ d: int [1:2, 1:2] 1 2 3 4
Accessing and Modifying Elements
Use [[]] for single elements and [] for sub-lists:
x <- list(a = 1, b = 2, c = 3)
# Double brackets return the element itself
x[["a"]] # 1 (numeric)
x[[1]] # 1 (same thing)
# Single brackets return a sub-list
x["a"] # List of 1
# Adding new elements
x$d <- 4
x[["e"]] <- 5
# Removing elements
x[["b"]] <- NULL
Converting Between Lists and Vectors
Use unlist() to flatten a list into a vector:
my_list <- list(a = c(1, 2), b = c(3, 4))
unlisted <- unlist(my_list)
unlisted
# a1 a2 b1 b2
# 1 2 3 4
Convert a vector to a list with as.list():
vec <- 1:3
as.list(vec)
# [[1]]
# [1] 1
# [[2]]
# [1] 2
# [[3]]
# [1] 3
Applying Functions to Lists
The lapply() function applies a function to each element, returning a list:
my_list <- list(a = 1:3, b = 4:6, c = 7:9)
lapply(my_list, sum)
# $a
# [1] 6
# $b
# [1] 15
# $c
# [1] 24
# sapply simplifies the result to a vector
sapply(my_list, sum)
# a b c
# 6 15 24
For more complex iteration, see the purrr functions reference.
Common Patterns
Returning Multiple Values from a Function
Lists are the standard way to return multiple objects:
calculate_stats <- function(x) {
list(
mean = mean(x),
median = median(x),
sd = sd(x),
n = length(x)
)
}
result <- calculate_stats(c(1, 2, 3, 4, 5))
result$mean # 3
result$median # 3
Storing Heterogeneous Data
Lists excel when you need to combine different data types:
person <- list(
name = "Bob",
age = 28,
skills = c("R", "Python", "SQL"),
contact = list(
email = "bob@example.com",
phone = "555-0123"
)
)