List (R)
A list is R's flexible container that can hold elements of different types and lengths — including other lists, vectors, data frames, and functions. Unlike a vector, its elements need not share a type.
R
Where an atomic vector forces every element to one type, a list can mix anything: numbers, strings, vectors, even nested lists or models. You build one with list(), optionally naming elements. This makes lists the natural structure for heterogeneous or hierarchical data, such as a parsed JSON object or a fitted model's output.
Indexing has two forms and the distinction trips up beginners: single brackets lst[1] return a sub-list (still a list), while double brackets lst[[1]] or lst$name extract the actual element inside. Use [[ ]] or $ when you want the value, [ ] when you want a list slice.
Many R objects are really lists under the hood — a data frame is a list of equal-length column vectors, and most model objects (from lm(), etc.) are lists of components you access by name. lapply() and sapply() iterate over list elements.
Syntax
lst <- list(name = "Ana", scores = c(90, 85))
lst$scoresExamples
R
person <- list(name = "Ana", ages = c(30, 31))
print(person$name)
print(person[["ages"]])
print(length(person))Output:
[1] "Ana"
[1] 30 31
[1] 2