R Lists

R Lists

Lists are an incredibly flexible, 1-dimensional data structure in R.

Unlike vectors, lists can securely hold elements of completely different data types!


Creating a List

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.

Creating a List Example:

# Mixing strings, numbers, and booleans!
my_list <- list("Apple", 42, TRUE, 10.5)

print(my_list)


Accessing List Elements

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!

Accessing Lists Example:

my_list <- list("Apple", "Banana", "Cherry")
# Extracts "Banana" as a raw string
second_item <- my_list[[2]]

print(second_item)


Changing and Adding Items

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.


Exercise 1 of 2

?

What is the primary difference between a Vector and a List in R?

Exercise 2 of 2

?

Which syntax correctly extracts the raw data value from the first position of a list?