List

A Beginner’s Guide

Author

Raju Rimal

Published

December 10, 2024

Modified

March 19, 2025

In R, lists are versatile data structures that allow you to store heterogeneous elements—such as numbers, characters, vectors, matrices, or even other lists—into a single object. Unlike vectors, which can only store elements of the same type, lists can store any type of data, making them ideal for more complex data representations. In this guide, we’ll walk you through how to create and manipulate lists, as well as access and modify nested elements, which are commonly found in real-world data like JSON, hierarchical data, or complex datasets.


1. Creating and Manipulating Lists

Lists are created using the list() function in R. You can mix and match various types of data within a single list—numbers, characters, vectors, and more.

Creating a List

  • Example:
# Create a simple list with different types of data
my_list <- list(
  name = "Alice",
  age = 30,
  scores = c(85, 90, 95),
  nested_list = list(location = "New York", hobby = "Painting")
)

# Print the list
print(my_list)
$name
[1] "Alice"

$age
[1] 30

$scores
[1] 85 90 95

$nested_list
$nested_list$location
[1] "New York"

$nested_list$hobby
[1] "Painting"

This list contains four elements: a character string, a numeric value, a vector of numbers, and another list. Lists can store any R object, which is why they’re so flexible.

Accessing List Elements

You can access elements of a list using the double square bracket [[ ]] for a specific element, or the single square bracket [ ] to return a sublist.

  • Example:
# Access a single element by name or index
name_value <- my_list[["name"]]
print(name_value)  # "Alice"
[1] "Alice"
# Alternatively, using the index
age_value <- my_list[[2]]
print(age_value)  # 30
[1] 30

To access a sublist, use single brackets [ ]:

  • Example:
# Access the 'nested_list' element as a sublist
nested_data <- my_list["nested_list"]
print(nested_data)
$nested_list
$nested_list$location
[1] "New York"

$nested_list$hobby
[1] "Painting"

Modifying List Elements

You can modify an existing element in a list or add new elements using similar methods.

  • Example:
# Modify an element in the list
my_list[["age"]] <- 31  # Change age to 31
print(my_list)
$name
[1] "Alice"

$age
[1] 31

$scores
[1] 85 90 95

$nested_list
$nested_list$location
[1] "New York"

$nested_list$hobby
[1] "Painting"
# Add a new element to the list
my_list[["email"]] <- "alice@example.com"
print(my_list)
$name
[1] "Alice"

$age
[1] 31

$scores
[1] 85 90 95

$nested_list
$nested_list$location
[1] "New York"

$nested_list$hobby
[1] "Painting"


$email
[1] "alice@example.com"

2. Accessing and Modifying Nested Elements

In real-world applications, you’ll often encounter lists that are nested—meaning a list contains other lists as its elements. These structures are often found in hierarchical data, JSON-like structures, or when working with datasets where each element has multiple attributes.

Accessing Nested List Elements

You can access nested elements using multiple levels of indexing with the [[ ]] operator. Each [[ ]] corresponds to a deeper level in the nested structure.

  • Example:
# Access the 'location' from the nested list
location_value <- my_list[["nested_list"]][["location"]]
print(location_value)  # "New York"
[1] "New York"

You can chain multiple levels of access, each using [[ ]], to reach deeply nested elements. For instance, if a list contains another list and that list contains a vector, you can access individual elements by navigating through the hierarchy.

Modifying Nested Elements

To modify a nested element, you can use a similar approach, specifying the list and its sublist.

  • Example:
# Modify the 'hobby' in the nested list
my_list[["nested_list"]][["hobby"]] <- "Reading"
print(my_list)
$name
[1] "Alice"

$age
[1] 31

$scores
[1] 85 90 95

$nested_list
$nested_list$location
[1] "New York"

$nested_list$hobby
[1] "Reading"


$email
[1] "alice@example.com"

Adding to Nested Lists

You can also add new elements to nested lists.

  • Example:
# Add a new item to the nested list
my_list[["nested_list"]][["city"]] <- "Los Angeles"
print(my_list)
$name
[1] "Alice"

$age
[1] 31

$scores
[1] 85 90 95

$nested_list
$nested_list$location
[1] "New York"

$nested_list$hobby
[1] "Reading"

$nested_list$city
[1] "Los Angeles"


$email
[1] "alice@example.com"

3. Working with More Complex Nested Structures

R lists can become quite complex, with multiple levels of nesting. In such cases, it’s helpful to use functions like lapply(), sapply(), and map() from the purrr package to traverse and manipulate nested lists more efficiently.

Using lapply() for Nested Lists

lapply() allows you to apply a function to each element of a list, including nested lists.

  • Example:
# Apply a function to modify the age of each person in a list of lists
people_list <- list(
  person1 = list(name = "Alice", age = 30),
  person2 = list(name = "Bob", age = 25)
)

updated_people <- lapply(people_list, function(x) {
  x$age <- x$age + 1  # Increment age by 1
  return(x)
})

print(updated_people)
$person1
$person1$name
[1] "Alice"

$person1$age
[1] 31


$person2
$person2$name
[1] "Bob"

$person2$age
[1] 26

This will increment the age of each person by 1, applying the function to all elements in the nested list.


4. Practical Use Cases of Lists

Lists are particularly useful when dealing with complex data structures like:

  • JSON Data: Lists can easily represent JSON-like hierarchical data, where each element might have a nested structure.
  • Data from APIs: When you retrieve data from web APIs, the result is often a nested list or JSON object.
  • Simulations and Modeling: In statistical modeling or simulations, lists can store model results, parameters, and metadata together.

Example: Working with a Nested JSON-Like Structure

Let’s assume you are dealing with a list that represents a JSON-like structure with nested data:

# Example JSON-like structure
json_data <- list(
  user = list(
    id = 1,
    name = "Alice",
    contact = list(email = "alice@example.com", phone = "123-456-7890")
  ),
  items = list(
    list(name = "Item1", price = 100),
    list(name = "Item2", price = 150)
  )
)

# Access nested elements
user_email <- json_data$user$contact$email
print(user_email)  # "alice@example.com"
[1] "alice@example.com"

This structure contains information about a user and a list of items. You can access the email of the user or the price of any item within the items list.


Summary

In this guide, you’ve learned:

  • How to create and manipulate lists: Lists can contain any data type and are created using the list() function.
  • Accessing and modifying list elements: You can use [[ ]] to access and modify individual elements, or [ ] for sublists.
  • Handling nested elements: Lists can contain other lists, and you can access or modify nested data using multiple levels of indexing.
  • Using lapply() to work with nested lists efficiently: Functions like lapply() can apply transformations to each element of a list, even if it’s nested.
  • Practical examples where lists are useful in real-world applications, such as handling hierarchical data or interacting with APIs.