Lists
A list is a bag that can hold different kinds of things of any size, like a backpack with a book, a lunch, and a ball. Unlike a vector, its items need not match.
In this page:
Syntax
list_name <- list(name1 = value1, name2 = value2)
list_name$name1
list_name[["name2"]]
Lists
A list can hold elements of different types and different lengths together, unlike a vector which requires uniform type.
Elements are accessed with double brackets, list[[i]], to get the value itself, while single brackets, list[i], return a sub-list. Lists are R's flexible general-purpose container, similar to a struct or heterogeneous array in other languages.
Warning:
- list[1] returns a list containing the first element.
- list[[1]] returns the element itself -- mixing these up is a very common bug.
Example: Lists
person <- list(name = "Alice", age = 30, active = TRUE)
print(person)
cat("Name:", person[["name"]], "\n")
cat("Name (dollar syntax):", person$name, "\n")
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
person["name"]and expecting the value, when single brackets return a list and[["name"]]or$namereturns the element. - Combining values with
c()when they have different types, so they are turned into one type instead of staying in alist(). - Assuming a list can be used in arithmetic like a vector, such as
person + 1, which is an error.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: