Lists
Lists hold elements of any type, including other lists — R's general-purpose container.
Lists hold elements of any type, including other lists — R's general-purpose container.
11.1 Creating & accessing
Analogy: if a list is a train, [ returns a smaller train; [[ returns the contents of one carriage.
person <- list(name = "Ann", age = 30, langs = c("R", "Python"), address = list(city = "Oslo"))
person$name # "Ann"
person[["age"]] # 30 — [[ ]] extracts the element
person["age"] # list(age = 30) — [ ] returns a sub-list
person$langs[2] # "Python"
person$address$city # nested access
person[["address"]][["city"]]
names(person); length(person); str(person)11.2 Modifying
person$email <- "[email protected]" # add
person$age <- NULL # remove
person[["langs"]] <- c(person$langs, "SQL")
modifyList(person, list(age = 31))
c(list(a = 1), list(b = 2)) # concatenate lists11.3 Working with lists
lst <- list(a = 1:3, b = 4:6, c = 7:9)
lapply(lst, mean) # list of means
sapply(lst, mean) # simplified to a named vector
vapply(lst, mean, numeric(1)) # type-safe sapply
unlist(lst) # flatten into a vector
rapply(list(1, list(2, 3)), \(x) x * 10, how = "unlist")
do.call(rbind, lst) # bind elements into a matrix
Reduce(`+`, lst) # element-wise sum of vectors
rlist <- setNames(vector("list", 3), c("x", "y", "z")) # pre-allocate11.4 Lists as return values & records
Most model objects (lm, t.test) are lists with a class attribute:
fit <- lm(mpg ~ wt, data = mtcars)
names(fit); fit$coefficients; class(fit)