Lists — Containers for Mixed Things
Plot A's record has a name, a crop, the weight of each picking and whether it was watered: text, a vector of numbers and a logical, all at once. A vector cannot hold that, because it holds one type. A list can hold anything, including other lists, and one bracket rule is all you need to use it.
The rule
[returns a smaller list;[[and$return the item inside.
plot_a <- list(
plot = "A",
crop = "tomato",
weighings = c(5, 4, 3.5), # three pickings, 12.5 kg in total
watered = TRUE
)
length(plot_a) # 4 items
plot_a$crop # "tomato"
plot_a[["weighings"]] # 5.0 4.0 3.5, the vector itself
plot_a[["weighings"]][2] # 4, second picking
plot_a["weighings"] # a list of length 1 that contains the vectorstr(plot_a) prints a compact outline of any list: each item's name, type and first values. It is the fastest way to understand a list someone else built.
Why the difference between one and two brackets matters:
sum(plot_a[["weighings"]]) # 12.5
sum(plot_a["weighings"]) # Error: invalid 'type' (list) of argumentThe first hands sum() a numeric vector; the second hands it a list, which it cannot add up.
Changing a list uses the same tools:
plot_a$notes <- "first ripe fruit in week 1" # add an item
plot_a$watered <- NULL # remove an itemAssigning NULL removes an item. Assigning NA would keep it, with an unknown value.
Lists show up everywhere in R. Many functions return their results as lists, and the data frame, which you will meet soon, is a list whose items are equal-length columns.
The shortcut
Picture the list as a train. Single brackets uncouple carriages: you still hold a train, only shorter. Double brackets, or $, open one carriage and hand you its cargo. When unsure, check with class().
Open the carriage
plot_a[["weighings"]]hands back the numeric vector 5 4 3.5.
Drills
Answer fast — trust the rule.
What is class(plot_a["crop"])?
What is plot_a$weighings[3]?
What is length(plot_a) for the original four-item list?
What does sum(plot_a[["weighings"]]) return?
How do you remove the watered item from plot_a?
Remember
[returns a smaller list;[[and$return the item inside.- Shortcut: a list is a train. One bracket uncouples carriages; two open one.
- Trap: passing a one-item list to a function that expects a vector.
