Lists

(Sections 9.1-9.2)

Lists

Non-Atomic Vectors

Lists: a new data structure in R.

Lists are non-atomic vectors. (Their elements don’t all have to be the same type of data.)

Example:

lst1 <- list(name = "Dorothy", age = 12)

lst1

lst1
$name
[1] "Dorothy"

$age
[1] 12

Another Example

df <- data.frame(x = c(10, 20, 30), y = letters[1:3])
lst2 <- list(vowels = c("a", "e", "i", "o", "u"),
             myFrame = df)
lst2
$vowels
[1] "a" "e" "i" "o" "u"

$myFrame
   x y
1 10 a
2 20 b
3 30 c

Yet Another Example

lst3 <- list(nums = 10:20,
             bools = c(TRUE, FALSE, FALSE),
             george = lst1)
lst3
$nums
 [1] 10 11 12 13 14 15 16 17 18 19 20

$bools
[1]  TRUE FALSE FALSE

$george
$george$name
[1] "Dorothy"

$george$age
[1] 12

Empty Lists

You can make an empty list, too:

emptyList <- list()
emptyList
list()

Accessing and Sub-Setting

Accessing List Elements

If a list element has a name, then you can get to it with the $:

lst1$age
[1] 12

Accessing

You can get to elements of a list inside a list in the same way:

lst3$george$age
[1] 12

Sub-Setting

This works with the [-operator (just as with vectors). The result is another list, as with vectors.

lst3[1:2]
$nums
 [1] 10 11 12 13 14 15 16 17 18 19 20

$bools
[1]  TRUE FALSE FALSE

Sub-Setting

lst3[1]
$nums
 [1] 10 11 12 13 14 15 16 17 18 19 20

Sub-setting a list yields another list, even when your numerical “location” vector has only one element.

Getting to the Contents of an Element

Two ways:

  • $ if the element has a name:
lst3$nums
 [1] 10 11 12 13 14 15 16 17 18 19 20
  • [[-operator always works.
lst3[[1]]
 [1] 10 11 12 13 14 15 16 17 18 19 20

Unlisting

This “flattens” the list into a vector:

lst1
$name
[1] "Dorothy"

$age
[1] 12
unlist(lst1)
     name       age 
"Dorothy"      "12" 

If elements are of different data types then they are coerced to be of the same type.