1 Goal


The goal of this tutorial is to create a list of lists. Being able to append a list inside of another list.


2 How to create a list


  # We can create a list easily using the list function
  my_list <- list(names = c("Name", "City", "Zip Code", "Street"), numbers = c(1:10))

  str(my_list)
## List of 2
##  $ names  : chr [1:4] "Name" "City" "Zip Code" "Street"
##  $ numbers: int [1:10] 1 2 3 4 5 6 7 8 9 10

3 How to create a list made of lists


  # First we create an empty list
  my_list_of_lists <- list()

  # Now we can add using the append function how many lists we want
  for(i in 1:5){
    my_list <- list(names = c("Name", "City", "Zip Code", "Street"), numbers = c(1:10 + 10*(i-1)))
    my_list_of_lists <- append(my_list_of_lists, list(my_list))
    names(my_list_of_lists)[i] <- paste0("my_list",i)
  }

  # Let's check what we got
  str(my_list_of_lists)
## List of 5
##  $ my_list1:List of 2
##   ..$ names  : chr [1:4] "Name" "City" "Zip Code" "Street"
##   ..$ numbers: num [1:10] 1 2 3 4 5 6 7 8 9 10
##  $ my_list2:List of 2
##   ..$ names  : chr [1:4] "Name" "City" "Zip Code" "Street"
##   ..$ numbers: num [1:10] 11 12 13 14 15 16 17 18 19 20
##  $ my_list3:List of 2
##   ..$ names  : chr [1:4] "Name" "City" "Zip Code" "Street"
##   ..$ numbers: num [1:10] 21 22 23 24 25 26 27 28 29 30
##  $ my_list4:List of 2
##   ..$ names  : chr [1:4] "Name" "City" "Zip Code" "Street"
##   ..$ numbers: num [1:10] 31 32 33 34 35 36 37 38 39 40
##  $ my_list5:List of 2
##   ..$ names  : chr [1:4] "Name" "City" "Zip Code" "Street"
##   ..$ numbers: num [1:10] 41 42 43 44 45 46 47 48 49 50

4 How to access the elements of the list


# If we want to access the elements of a list we must use double squared bracket[[]]
my_list_of_lists[[1]]
## $names
## [1] "Name"     "City"     "Zip Code" "Street"  
## 
## $numbers
##  [1]  1  2  3  4  5  6  7  8  9 10
# We see that the first element of the list is a list
# Let's go deeper
# Now we can access the first element of the second list
my_list_of_lists[[1]][1]
## $names
## [1] "Name"     "City"     "Zip Code" "Street"
# However this is still a list
str(my_list_of_lists[[1]][1])
## List of 1
##  $ names: chr [1:4] "Name" "City" "Zip Code" "Street"
# We can access the vector inside of the list using the double bracket
str(my_list_of_lists[[1]][[1]])
##  chr [1:4] "Name" "City" "Zip Code" "Street"
# Now we can go deeper and access one element of the character vector inside of the list
# This should return the character "Zip Code"
my_list_of_lists[[1]][[1]][3]
## [1] "Zip Code"
# Using the same logic this query should return the number 24
my_list_of_lists[[3]][[2]][4]
## [1] 24

5 Conclusion


In this tutorial we have learnt how to access elements inside of a list. We have learnt how to create a list of lists and access each diferent element of the list.