How to create a list of lists in R

The list data structure in R allows the user to store homogeneous (of the same type) or heterogeneous (of different types) R objects. Therefore, a list can contain objects of any type including lists themselves.

svg viewer

Code

Method 1

In the code snippet below, two lists are created and then combined into another list. The output shows that animals is a list containing two elements, mammals is a list containing three elements, ​and amphibians is a list containing one element.

# Creating a list
mammals <- list("cat", "dog", "bear")
# Creating another list
amphibians <- list("frog")
# Creating a list of lists
animals <- list(mammals, amphibians)
# Printing the list
cat(str(animals))

Method 2

The lists that are to be contained in another list can be created inline. Moreover, titles can be assigned to the list elements, as shown below. Note that mammals and amphibians are titles of the lists created inline.

# Creating a list
# Creating a list of lists
animals <- list(mammals = list("cat", "dog", "bear"), amphibians = list("frog"))
# Printing the list
cat(str(animals))

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved