(l1 <- list(1, 2, 3))[[1]]
[1] 1
[[2]]
[1] 2
[[3]]
[1] 3
(l2 <- list("bob", TRUE, 33, 42 + 3i))[[1]]
[1] "bob"
[[2]]
[1] TRUE
[[3]]
[1] 33
[[4]]
[1] 42+3i
(l3 <- list(c(1, 2), c(3, 4)))[[1]]
[1] 1 2
[[2]]
[1] 3 4
Lists place essentially no restrictions on the nature of their contents:
So, lists are a great way to store substantively related, but heterogeneously sized/typed, pieces of data in one object.
We construct lists using the list() function.
[[1]]
[1] 1
[[2]]
[1] 2
[[3]]
[1] 3
[[1]]
[1] "bob"
[[2]]
[1] TRUE
[[3]]
[1] 33
[[4]]
[1] 42+3i
[[1]]
[1] 1 2
[[2]]
[1] 3 4
Create a list called myList that comprises the following three elements.
We can name the elements of a list by defining the list slots via key-value pairs.
$name
[1] "bob"
$alive
[1] TRUE
$age
[1] 33
$relationshipStatus
[1] 42+3i
We can use the names() function to access and modify the names of a list’s slots.
NULL
[[1]]
[1] 1
[[2]]
[1] 2
[[3]]
[1] 3
$first
[1] 1
$second
[1] 2
$third
[1] 3
The names() function returns a character vector. So, we can assign/overwrite a subset of the names using ordinary vector subsetting syntax.
[1] "name" "not dead" "age"
[4] "relationshipStatus"
$name
[1] "bob"
$`not dead`
[1] TRUE
$age
[1] 33
$relationshipStatus
[1] 42+3i
Consider the following list (aList) when answering this question.
Predict what the following code will print.
Use the interactive editor to check your predictions.
We’ve overwritten the names of the second and third list slots with the new values blue and hey, respectively. So, we see an updated version of aList that contains the same data but has two new names.
$hello
[1] "world"
$blue
[1] "monday"
$hey
[1] "jude"
$false
[1] TRUE
It’s difficult to overstate the versatility of lists as general-purpose containers for R objects. It’s no exaggeration to say that a list can store any type of R object. Notably, lists are perfectly happy to store other lists. So the following abomination is a completely valid list.
Create a list to describe yourself. Include the following named elements in your list: