2.5 Lists
Lists are the ultimate data type in R. They are actually a vector that can hold different kinds of data, like a dataframe. In fact, a dataframe is just a spectacularly rectangular list. Each element of a list can be any kind of object (an atomic vector, a matrix, a dataframe, or even another list!!).
Most of the real, filthy R programming relies heavily on lists. We will have to work with them at some point in this class, but we won’t take a ton of time on them here.
Let’s make a list- just to see how they work. Notice how our index operator has changed from [ ]
to [[ ]]
? And, at the highest level of organization, we have only one dimension in our list, but any given element myList[[i]]
could hold any number of dimensions.
# Create an empty list with four elements
myList <- vector(mode = "list", length = 4)
# Assign some of our previously
# created objects to the elements
myList[[1]] <- a
myList[[2]] <- c
myList[[3]] <- mat
myList[[4]] <- d
Have a look at the list:
## [[1]]
## [1] 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 7.5
## [16] 8.0 8.5 9.0 9.5 10.0
##
## [[2]]
## [1] "a" "b" "c" "d" "a" "b" "c" "d" "a" "b" "c" "d" "a" "b" "c" "d" "a" "b" "c"
## [20] "d"
##
## [[3]]
## first second third
## This 1 5 9
## is 2 6 10
## a 3 7 11
## matrix 4 8 12
##
## [[4]]
## a b c
## 1 0.5 0.25 a
## 2 1.0 1.00 b
## 3 1.5 2.25 c
## 4 2.0 4.00 d
## 5 2.5 6.25 a
## 6 3.0 9.00 b
## 7 3.5 12.25 c
## 8 4.0 16.00 d
## 9 4.5 20.25 a
## 10 5.0 25.00 b
## 11 5.5 30.25 c
## 12 6.0 36.00 d
## 13 6.5 42.25 a
## 14 7.0 49.00 b
## 15 7.5 56.25 c
## 16 8.0 64.00 d
## 17 8.5 72.25 a
## 18 9.0 81.00 b
## 19 9.5 90.25 c
## 20 10.0 100.00 d
You can assign names when you create the list like we did for dataframes, too. You can do this manually, or R will do it on the fly for you. You can also reassign names to a list that yo’ve already created.
# No names by default
names(myList)
# Give it names like we did with
# a dataframe
names(myList) <- c("a", "c", "mat", "d")
# See how the names work now?
myList
# We reference these differently [[]]
myList[[1]]
# But we can still get into each object
# Play around with the numbers to see what they do!
myList[[2]][5]
# Can also reference it this way!
myList$c[1]
Very commonly, model objects and output are stored as lists. In fact, most objects that require a large amount of diverse information in R pack it all together in one place using lists, that way we always know where to find it and how as long as the objects are documented. Conceptually, every object in R, from your workspace on down the line, is a list AND an element of a list. It seems like a lot to take in now, but will be very useful in the future.