Lists in
R Programming
Master R's most flexible data structure: create lists that hold mixed types, and access elements with \(\texttt{[]}\), \(\texttt{[[ ]]}\), and \(\texttt{\$}\).
What Is a List?
In R, a list is an ordered collection of elements that can each hold a different data type: numbers, strings, vectors, data frames, or even other lists. Unlike vectors, which require all elements to be the same type, lists are R's most flexible container.
Why Lists Matter
Lists vs Vectors
Creating a List
Three Ways to Access Elements
\(\texttt{[]}\) : Single Bracket
\(\texttt{[[ ]]}\) : Double Bracket
\(\texttt{\$}\) : Dollar Sign Operator
\(\texttt{[]}\) vs \(\texttt{[[ ]]}\) : The Key Difference
How to Choose an Operator
Example 1: Building a List
Example 2: Nested Access
Example 3: Modifying Lists
Common Mistakes
Summary Comparison
| Feature | \(\texttt{[]}\) | \(\texttt{[[ ]]}\) | \(\texttt{\$}\) |
|---|---|---|---|
| Returns | Sub-list | Raw value | Raw value |
| Multiple elements | ✓ Yes | ✕ No | ✕ No |
| By index | ✓ Yes | ✓ Yes | ✕ No |
| By name | ✓ Yes | ✓ Yes | ✓ Yes |
| With variable | ✓ Yes | ✓ Yes | ✕ No |
| Quotes needed | For names | For names | Never |
Question 1 of 5
Given \(\texttt{my\_list <- list(a = 10, b = "hello", c = TRUE)}\), what does \(\texttt{my\_list[1]}\) return?
Question 2 of 5
Which operator would you use to extract the raw value of a named element from a list using a variable that stores the element's name?
Question 3 of 5
Given \(\texttt{info <- list(x = c(5, 10, 15), y = "test")}\), what does \(\texttt{info\$x[2]}\) return?
Question 4 of 5
What is the correct way to add a new element called \(\texttt{score}\) with value \(\texttt{95}\) to an existing list called \(\texttt{record}\)?
Question 5 of 5
What is the key difference between a list and an atomic vector in R?