Creating Lists

Generating Lists

We construct lists using the list() function. Lists place essentially no restrictions on the nature of their contents:

  • A list slot can hold any valid R object (including other lists).
  • The contents of different list slots do not need to have the same type (nor do they need to be different types).
  • The contents of different list slots do not need to have the same—or otherwise conformable—sizes.
(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

Naming List Elements

We can name the elements of a list by defining the list slots via key-value pairs.

l4 <- list(name = "bob",
           alive = TRUE,
           age = 33,
           relationshipStatus = 42+3i)
l4
$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.

names(l4)
[1] "name"               "alive"              "age"               
[4] "relationshipStatus"
names(l1) <- c("first", "second", "third")
l1
$first
[1] 1

$second
[1] 2

$third
[1] 3
Practice

Create a list to describe yourself. Include the following named elements in your list:

  1. Your Name
  2. Your Eye Color
  3. Your Hair Color
  4. Your Favorite Color
myInfo <- list(name = "bob",
               eyes = "blue",
               hair = "black",
               color = "green")
myInfo
$name
[1] "bob"

$eyes
[1] "blue"

$hair
[1] "black"

$color
[1] "green"
Back to top