R Lists

A list lets you group values of different types and lengths together under one name, unlike a vector which requires uniformity.

What Makes a List Different from a Vector

A vector demands that every element share the same type, but a list has no such rule. A single list can hold a number, a character string, a logical value, and even another vector or list, all at once. You create one with the list() function.

Example

student <- list(name = "Priya", age = 21, passed = TRUE, grades = c(88, 91, 79))
student

length(student)

Accessing List Elements: [ ] vs [[ ]]

Single brackets [ ] pull out a sub-list - the result is still a list, just a smaller one. Double brackets [[ ]] reach inside and return the actual element itself, stripped of its list wrapper. This distinction trips up a lot of beginners, so it's worth testing both on the same list to see the difference.

Comparing [ ] and [[ ]]

student <- list(name = "Priya", age = 21, passed = TRUE)

student[1]     # a list containing one element
student[[1]]   # the character value "Priya" itself

class(student[1])
class(student[[1]])
  • student[1] returns a list of length one
  • student[[1]] returns the raw value stored at that position
  • student["name"] returns a list, matched by name
  • student[["name"]] returns the raw value, matched by name

Named Lists and the $ Shortcut

When a list's elements have names, the $ operator gives you a shorter way to reach into it than typing the name inside double brackets. student$age and student[["age"]] return exactly the same thing - $ is just quicker to type and read.

Using $

student <- list(name = "Priya", age = 21, grades = c(88, 91, 79))

student$name
student$grades[2]

student$age <- 22
student$age
Note: unlist() flattens a list back into a single vector, which is handy when every element turns out to be the same type after all. Remember it coerces everything to the most general type present, so mixing numbers and text produces a vector of text.
FunctionWhat it does
list()Creates a list
length(x)Number of top-level elements
names(x)Names of the elements, if any
unlist(x)Flattens a list into a vector

Exercise: R Lists

What is a key advantage a list has over a vector in R?