Lesson 4d - Lists
Lists are another type of container that R has to offer.
Table of Contents
Lesson Objectives
- Use lists to create containers with elements of multiple data types
What is a List?
A list is a container that can contain elements of different data types, unlike vectors.
Creating a List
The format to create a list is the following:
myList = list(value1, value2, value3, ...)
Storing Values by Name
Just like with vectors, we can give values keys so that we can reference them by name later on.
myList = list(a = "apple", b = 2, c = TRUE)
Accessing Items in a List
Lists are strange when it comes to indexing.
Input
myList <- list(2, 2, 3, "a string", TRUE)
# if we were to access the first index like normal, we would get a list of 1 element
myList[1]
Output
[[1]]
[1] 2
To get the actual value, we need to use double square brackets [[ ]].
Input
myList <- list(2, 2, 3, "a string", TRUE)
myList[[1]]
Output
[1] 2
This makes a huge difference when you’re using the values given to you.
Input
myList <- list(2, 2, 3, "a string", TRUE)
myList[[1]] + 1 # Correct
myList[1] + 1 # Incorrect
Output
[1] 3
Error in myList[1] + 1 : non-numeric argument to binary operator
Accessing Values by Name
Input
myList = list(a = "apple", b = 2, c = TRUE)
myList[["a"]]
Output
[1] "apple"
Accessing Multiple Items
Input
myList = list(2, 2, 3, "a string", TRUE)
myList[c(1, 2, 4)] # Creates a new list with only items #1, #2, and #4
Output
[[1]]
[1] 2
[[2]]
[1] 2
[[3]]
[1] "a string"
Modifying Values in a List
The process to modify values in a list is identical to how matrices and vectors have their values modified. Index the item you want to change and assign it to a new value.
Input
myList = list(2, 2, 3, "a string", TRUE)
myList[[3]] <- "another string"
myList
Output
[[1]]
[1] 2
[[2]]
[1] 2
[[3]]
[1] "another string"
[[4]]
[1] "a string"
[[5]]
[1] TRUE
Adding Elements to a List
There are several ways to add elements to a list. If we simply want to add a new element at the end of a list, we can use the append()
function.
Input
myList = list(2, 3)
myList <- append(myList, 4)
myList
Output
[[1]]
[1] 2
[[2]]
[1] 3
[[3]]
[1] 4
You can also use the append function to insert a new element at a specific position by setting after
to your desired index.
Input
myList = list(2, 3)
myList <- append(myList, 4, after=1)
myList
Output
[[1]]
[1] 2
[[2]]
[1] 4
[[3]]
[1] 3
Finally, you can also add a new element to a list by assigning a value to its named index directly.
Input
myList = list(a = "apple", b = "banana")
myList["c"] <- "cookie"
myList
Output
$a
[1] "apple"
$b
[1] "banana"
$c
[1] "cookie"
Key Points / Summary
- Lists should be used when you need to store data of multiple data types