R by Example: Lists
Managing heterogeneous collections with this sample code demonstrating list creation with mixed element types, single versus double bracket indexing behavior, dollar sign access for named elements, and dynamic list modification.
Code
# Creating a list
my_list <- list(
name = "Experiment A",
scores = c(85, 90, 92),
matrix_data = matrix(1:4, nrow=2),
passed = TRUE
)
# Accessing elements
# Single brackets return a list
sub_list <- my_list[1]
# Double brackets return the actual content
name_val <- my_list[[1]]
scores_vec <- my_list[["scores"]]
# Dollar sign also returns content
mat <- my_list$matrix_data
# Modifying lists
my_list$new_item <- "Added later"
my_list[[2]] <- c(88, 91, 95)Explanation
Lists are one-dimensional but highly flexible data structures that can contain elements of different types and structures including vectors, matrices, data frames, functions, and even other lists. This heterogeneity makes lists ideal for storing complex hierarchical data, such as the output from statistical models which often contain multiple components of different types. Lists maintain element order and can have named or unnamed elements.
List indexing distinguishes between single brackets [] and double brackets [[]] with fundamentally different behaviors. Single brackets always return a list containing the selected elements, preserving the list structure. Double brackets extract the actual object stored at that position, removing one level of list hierarchy. For example, my_list[1] returns a list of length 1, while my_list[[1]] returns the object itself. The dollar sign $ operator provides convenient access to named elements and is equivalent to double bracket notation.
Lists can be created using the list() function and modified dynamically by assigning to new or existing indices. Named elements can be accessed by name using either [[name]] or $name syntax. Lists are actually the underlying structure for data frames, which are lists of vectors with additional constraints requiring equal length and rectangular structure.
Code Breakdown
list() creates heterogeneous collection with mixed types.my_list[1] returns list of length 1 preserving structure.my_list[[1]] extracts actual object, removing list wrapper.$new_item dynamically adds named element to existing list.
