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.
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 listmammals <- list("cat", "dog", "bear")# Creating another listamphibians <- list("frog")# Creating a list of listsanimals <- list(mammals, amphibians)# Printing the listcat(str(animals))
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 listsanimals <- list(mammals = list("cat", "dog", "bear"), amphibians = list("frog"))# Printing the listcat(str(animals))
Free Resources