Lists are an incredibly flexible, 1-dimensional data structure in R.
Unlike vectors, lists can securely hold elements of completely different data types!
To construct a list, you use the built-in list() function.
You can seamlessly mix numbers, strings, booleans, and even other entire vectors inside a single list.
This makes lists the perfect structure for storing complex, heterogeneous data records.
# Mixing strings, numbers, and booleans!
my_list <- list("Apple", 42, TRUE, 10.5)
print(my_list)
Because lists are more complex than vectors, accessing their elements is slightly different.
To extract a single element as its original data type, you must use double square brackets [[ ]].
If you use single brackets [ ], R returns a new, smaller list containing that item, not the raw value itself!
my_list <- list("Apple", "Banana", "Cherry")
# Extracts "Banana" as a raw string
second_item <- my_list[[2]]
print(second_item)
Lists are highly mutable, meaning they can be changed after they are created.
You can add a brand new item to the end of a list using the append() function.
What is the primary difference between a Vector and a List in R?
Which syntax correctly extracts the raw data value from the first position of a list?