Chapter 6 Lists

A list is like an array but it can contain multiple types of elements.

6.1 Make a list

x = list(
  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

x['a'] # by key name
#> $a
#> [1] 5
x[1]   # by index
#> $a
#> [1] 5

Multiple keys

x[c('b', 'a')] # by key name
#> $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 .

x$Long_Name
#> [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.

x[['a']] # by key name
#> [1] 5
x[[1]]   # by index
#> [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

myList = list(a=1, b=2, c=3, d=4)
as.vector(unlist(myList))
#> [1] 1 2 3 4