Chapter 6 Lists
A list is like an array but it can contain multiple types of elements.
6.1 Make a list
= list(
x a = 5,
b = 2,
Long_Name = 4.8,
"named with spaces" = 0,
12, # not every element needs a name
a = 20 # names don't have to be unique (but you really should avoid this)
)
6.2 Accessing elements in a list
Get a tuple of the key and value
'a'] # by key name x[
#> $a
#> [1] 5
1] # by index x[
#> $a
#> [1] 5
Multiple keys
c('b', 'a')] # by key name x[
#> $b
#> [1] 2
#>
#> $a
#> [1] 5
Type the list name, then $
, and press tab. R will pop up a list of keys to autocomplete.
R uses $
in the way that other languages use .
$Long_Name x
#> [1] 4.8
Note: Only the value is returned.
6.3 Brackets for real
Sometimes, R will return the whole list or object even though you asked for just one element. So you need to use double brackets. Why? Because R is snarky and doesn’t believe you actually want what you said. So you need to use double brackets to explain to R that you’re sure this is what you want.
Double brackets only works for single items, not subsetting.
'a']] # by key name x[[
#> [1] 5
1]] # by index x[[
#> [1] 5
6.4 Names and values
Use the names()
function to get and set names. It behaves like an array.
names(x)
#> [1] "a" "b" "Long_Name"
#> [4] "named with spaces" "" "a"
names(x)[3]
#> [1] "Long_Name"
You can modify names by assigning strings to the names function. This is weird. Take a minute to let it sink in.
names(x) = c("first", "second", "third", "fourth")
names(x)[3] = "new name"
If all elements are the same type, this will get a vector of values
= list(a=1, b=2, c=3, d=4)
myList as.vector(unlist(myList))
#> [1] 1 2 3 4