R — Lists
What is a list?
A list is an ordered collection that can hold any type of R object — numbers, strings, vectors, matrices, other lists:
person <- list(
name = "Ada",
age = 36,
scores = c(90, 85, 95),
active = TRUE
)
Lists are R's equivalent of dictionaries in Python or objects in JavaScript.
Creating lists
# With names
person <- list(name = "Ada", age = 36, job = "Engineer")
# Without names
simple <- list(1, "hello", TRUE)
# From existing objects
x <- 42
y <- "hello"
z <- c(1, 2, 3)
my_list <- list(x, y, z)
# Empty list
empty <- list()
Accessing list elements
person <- list(name = "Ada", age = 36, scores = c(90, 85, 95))
# By name — returns a list
person["name"] # list with name element
person[["name"]] # "Ada" — extracts the value
person$name # "Ada" — same as [[
# By index
person[[1]] # "Ada"
person[[3]] # 90 85 95
# Multiple elements
person[c("name", "age")] # sublist
person[c(1, 2)] # sublist
The key difference: person["name"] returns a list; person[["name"]] returns the value. Use [[ when you want the actual data.
Modifying lists
person <- list(name = "Ada", age = 36)
# Add elements
person$email <- "ada@example.com"
person[["job"]] <- "Engineer"
# Change elements
person$age <- 37
# Remove elements
person$email <- NULL
# Add at position
person <- append(person, list(city = "London"), after = 1)
List functions
x <- list(1, 2, 3, 4, 5)
length(x) # 5
names(x) # NULL (unnamed)
# Name the elements
names(x) <- c("a", "b", "c", "d", "e")
# str — structure
str(person)
# unlist — flatten to a vector
unlist(x) # 1 2 3 4 5
# lapply — apply function to each element
squares <- lapply(1:5, function(x) x^2)
# returns a list
# sapply — simplified version (returns vector when possible)
squares <- sapply(1:5, function(x) x^2)
# returns a vector
Nested lists
Lists can contain other lists:
company <- list(
name = "TechCorp",
employees = list(
list(name = "Ada", role = "Engineer"),
list(name = "Grace", role = "Scientist")
)
)
# Access nested elements
company$employees[[1]]$name # "Ada"
company$employees[[2]]$role # "Scientist"
Lists vs vectors
| Feature | Vector | List |
|---|---|---|
| Element type | Same type | Any type |
| Access | x[1] returns vector | x[[1]] returns value |
| Speed | Faster | Slower |
| Use case | Homogeneous data | Heterogeneous data |
Unlisting
x <- list(a = 1, b = 2, c = 3)
unlist(x) # named vector: a b c \n 1 2 3
# Flatten nested lists
nested <- list(list(1, 2), list(3, 4))
unlist(nested) # 1 2 3 4
Converting between types
# Vector to list
v <- c(1, 2, 3)
lst <- as.list(v)
# List to vector (when elements are compatible)
lst <- list(1, 2, 3)
v <- unlist(lst)
# List to data frame (when elements are same length)
lst <- list(a = 1:3, b = 4:6)
df <- as.data.frame(lst)
Common patterns
Building lists dynamically
results <- list()
for (i in 1:5) {
results[[i]] <- i^2
}
Filtering lists
numbers <- list(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
# Keep only even numbers
evens <- Filter(function(x) x %% 2 == 0, numbers)
# returns list(2, 4, 6, 8, 10)
# Find first match
first_even <- Position(function(x) x %% 2 == 0, numbers)
# returns 2 (index)
Combining lists
a <- list(1, 2, 3)
b <- list(4, 5, 6)
c(a, b) # list of 6 elements
# Merge named lists
x <- list(a = 1, b = 2)
y <- list(b = 3, c = 4)
c(x, y) # list(a=1, b=3, c=4) — y's b overwrites x's
Recursive flattening
flatten_list <- function(lst) {
result <- list()
for (item in lst) {
if (is.list(item)) {
result <- c(result, flatten_list(item))
} else {
result <- c(result, list(item))
}
}
result
}
nested <- list(1, list(2, list(3, 4)), 5)
flatten_list(nested) # list(1, 2, 3, 4, 5)
Lists in real R code
Lists are everywhere in R:
# Linear model output is a list
model <- lm(mpg ~ wt, data = mtcars)
str(model) # list with coefficients, residuals, etc.
# File reading returns lists
config <- jsonlite::fromJSON("config.json")
# Functions can return lists for multiple outputs
analyze <- function(x) {
list(
mean = mean(x),
sd = sd(x),
n = length(x)
)
}
result <- analyze(rnorm(100))
result$mean # average of the random sample
Mini Practice
- Create a list with your name, age, and a vector of your hobbies
- Access each element using
$,[[, and[— explain the differences - Add a new element and remove an existing one
- Use
lapplyto square each number in a list - Create a nested list representing a book with chapters and pages
Next: matrices — 2D data →
Related Topics
Frequently Asked Questions about Lists
What is Lists in R?
Lists is a fundamental concept in R. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Lists?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Lists.
Why is Lists important in R?
Lists is essential for R development. Understanding this concept will help you write better code and solve real-world problems more effectively.