← Back to R Course | Chapter 7: Data Structures | Lesson 2 of 7

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:

  1. Lists
Syntax
r
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

markup
person <- list(name = "Alice", age = 30, active = TRUE)

print(person)
cat("Name:", person[["name"]], "\n")
cat("Name (dollar syntax):", person$name, "\n")
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
  1. Using person["name"] and expecting the value, when single brackets return a list and [["name"]] or $name returns the element.
  2. Combining values with c() when they have different types, so they are turned into one type instead of staying in a list().
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.