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 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))
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
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))
View all Courses