Lists (optional)

Optional. You don’t need this before Week 1. Come back to it for a head start on later weeks, or as a refresher.

Lists

A list is like a vector, but its elements can be anything: a number, some text, a whole vector, even another list. Make one with list(), usually naming the elements:

site <- list(name = "Durham", elevation_m = 102, temps = c(3.2, 3.8, 5.9))

Take an element out by name with $ (as in site$name) or with double brackets (as in site[["temps"]]). Single brackets, as in site["temps"], return a smaller list rather than the element itself.

If you have used Python, a named list is close to a dict.

Lists matter because a data frame is a list of equal-length vectors, one per column. That is why df$column works.

Run the chunk below, then extract the mean of site$temps.

Lists vs. vectors

Which data structure(s) could you use to store these pieces of data in the same object? 1001, TRUE, "stories"




Make a list

Make a list that contains the elements 1001, TRUE, and "stories". Give each element a name.

list(number = 1001, logical = TRUE, string = "stories")

Extract an element

Extract the number 1001 from the list below.

things <- list(number = 1001, logical = TRUE, string = "stories")
things$number

Data Frames

You can make a data frame with the data.frame() function, which works similar to c(), and list(). Assemble the vectors below into a data frame with the column names numbers, logicals, strings.

nums <- c(1, 2, 3, 4)
logs <- c(TRUE, TRUE, FALSE, TRUE)
strs <- c("apple", "banana", "carrot", "duck")
data.frame(numbers = nums, logicals = logs, strings = strs)

Good job. When you make a data frame, you must follow one rule: each column vector should be the same length

Extract a column

Given that a data frame is a type of list (with named elements), how could you extract the strings column of the df data frame below? Do it.

df$strings

Next topic