Introduction to Lists in R. Lists can hold components of different... | by Linda Ngo | Towards Data Science

Lists can hold components of different types. Learn how to create, name, and subset these lists.
There are a couple of data structures that you can use to hold data:
Vectors (one dimensional array) — vectors can hold numeric, character, or logical values, but their elements must all be the same data type.
Matrices (two dimensional array) — just like vector elements, matrices can hold numeric, character, or logical values; however, their elements must all be the same data type.
Data frames (two-dimensional objects) — data frames can hold numeric, character, or logical values. Within a column, all elements must have the same data type, but different columns can be of a different data type.
Lists ( super data type) — lists allow different objects, such as matrices, vectors, data frames, and other lists, to be gathered under one name (the name of the list) in an ordered way. None of these objects needs to be related in any way. As such, you can store practically anything in a list.
We use the function list() to construct a list:
my_list <- list(comp1, comp2, ...)
The arguments to the list() function are the list components ( comp1, comp2,... ). They can be matrices, vectors, other lists, etc.
Suppose we want to create a list ( my_list ) that contains the following as list components: my_vector , my_matrix , and my_df .
# Vector with numerics from 1 up to 10my_vector <- 1:10# Matrix with numerics from 1 up to 9my_matrix <- matrix(1:9, ncol = 3)# First 10 elements of the built-in data frame mtcarsmy_df <- mtcars[1:10,]
To construct the list, we again use the list() function:
# Construct list with these different elements:my_list <- list(my_vector, my_matrix, my_df)
Giving names to the components in a list ensures that we won’t forget what they stand for. We can either name our components during the construction of the list or afterwards. For example,
# Name components directly during list construction.my_list <- list(name1 = your_comp1,                 name2 = your_comp2)
creates a list with components named name1, name2 , and so on. To name the list after we’ve created them, we use the names() function like we did with vectors. This will accomplish the same thing we did above:
# Use names() function to name list after constructionmy_list <- list(your_comp1, your_comp2)names(my_list) <- c("name1", "name2")
Add names to components of my_list . you can use the names vec, mat, and df for my_vector, my_matrix, and my_df, respectively.
# Vector with numerics from 1 up to 10my_vector <- 1:10# Matrix with numerics from 1 up to 9my_matrix <- matrix(1:9, ncol = 3)# First 10 elements of the built-in data frame mtcarsmy_df <- mtcars[1:10,]# Construct list with these different elements:my_list <- list(my_vector, my_matrix, my_df)
# Vector with numerics from 1 up to 10my_vector <- 1:10# Matrix with numerics from 1 up to 9my_matrix <- matrix(1:9, ncol = 3)# First 10 elements of the built-in data frame mtcarsmy_df <- mtcars[1:10,]# Adapt list() call to give the components namesmy_list <- list(my_vector, my_matrix, my_df)names(my_list) <- c("vec", "mat", "df")# Print out my_listmy_list
Create a list for the movie “The Shining”, which contains three components:
moviename — a character string with the movie title (stored in mov )
actors — a vector with the names of the main actors (stored in act)
reviews — a data frame that contains some reviews (stored in rev)
# Character variable for movie namemov <- "The Shining"# Vector for the names of the movie actorsact <- c("Jack Nicholson", "Shelley Duvall", "Danny Lloyd", "Scatman Crothers", "Barry Nelson")# Data frame of the movie reviewsscores <- c(4.5, 4.0, 5.0)sources <- c("IMDb1", "IMDb2", "IMDb3")comments <- c("Best Horror Film I have Ever Seen", "A truly brilliant and scary film from Stanley Kubrick", "A masterpiece of psychological horror")rev <- data.frame(scores, sources, comments)
Don’t forget to name the list components accordingly (moviename, actors, and reviews).
Do not forget to name the list components accordingly (names are moviename, actors and reviews).
# Character variable for movie namemov <- "The Shining"# Vector for the names of the movie actorsact <- c("Jack Nicholson", "Shelley Duvall", "Danny Lloyd", "Scatman Crothers", "Barry Nelson")# Data frame of the movie reviewsscores <- c(4.5, 4.0, 5.0)sources <- c("IMDb1", "IMDb2", "IMDb3")comments <- c("Best Horror Film I have Ever Seen", "A truly brilliant and scary film from Stanley Kubrick", "A masterpiece of psychological horror")rev <- data.frame(scores, sources, comments)# Shining Listshinning_list <- list(moviename = mov, actors = act, reviews = rev)shinning_list
A list is often built out of numerous elements and components; so, it is not always straightforward getting a single element, multiple elements, or a component from it.
One way to select a component is using the numbered position of the component. For example, to select the first component (position 1), we would use:
my_list[[1]]
Notice that this is different than with vectors and matrices which use single square brackets [] as opposed to double square brackets [[]] .
We can also use the names of the components instead of the position. We can use either [[]] or with $ . For example, the following will both select the reviews components from the shining_list .
shining_list[["reviews"]]shining_list$reviews
Sometimes, you want to drill into the component and select specific elements from the selected component. For example, suppose we want to select the first element from the array of actors from the shining_list . The array actors is the second component so it can be accessed using shining_list[[2]]. Since this component is also named, we could’ve used shining_list$actors to get the same result.
Since we want the select the first element [1] from that component, we would use shining_list[[2]][1] or shining_list$actors[1].
Given the shining_list below, select the actors vector and print it out. Then select the second element from this vector and print it out.
# Character variable for movie namemov <- "The Shining"# Vector for the names of the movie actorsact <- c("Jack Nicholson", "Shelley Duvall", "Danny Lloyd", "Scatman Crothers", "Barry Nelson")# Data frame of the movie reviewsscores <- c(4.5, 4.0, 5.0)sources <- c("IMDb1", "IMDb2", "IMDb3")comments <- c("Best Horror Film I have Ever Seen", "A truly brilliant and scary film from Stanley Kubrick", "A masterpiece of psychological horror")rev <- data.frame(scores, sources, comments)# Shining Listshinning_list <- list(moviename = mov, actors = act, reviews = rev)
# Print out the vector representing the actorsshining_list$actors# Print the second element of the vector representing the actorsshining_list$actors[2]
Here’s a challenge to put what you’ve learned to the test!
Suppose you have found reviews of another, more recent, Jack Nicholson movie: The Departed!
The actors in this movie are:
Leonardo DiCaprio
Matt Damon
Jack Nicholson
Mark Wahlberg
Vera Farmiga
Martin Sheen
Here are the reviews:
Would watch it again — 4.61
Amazing! — 5
I liked it — 4.81
One of the best movies — 5
Fascinating plot — 4.2
It would be useful to collect together all the pieces of information about the movie, like the title, actors, and reviews, into a single variable. Since these pieces of data are different types, we will have to combine them in a list variable.
Now, using the information given above, here’s what you’re going to have to do:
Create a variable, called movie_title containing the title of the movie.
Create a vector, called movie_actors , containing the names of the actors listed above.
Create two vectors, called scores and comments, that contain the information from the reviews shown above.
Find the average of the review scores ( scores vector)and save it as avg_review.
Create a reviews data frame called reviews_df that combines scores and comments .
Create a list, called departed_list, that contains the movie_title , movie_actors , reviews data frame as reviews_df , and the average review score as avg_review , and print it out.
# Use the given movie information above to define the movie title and movie actorsmovie_title <- "The Departed"movie_actors <- c("Leonardo DiCaprio", "Matt Damon", "Jack Nicholson", "Mark Wahlberg", "Vera Farmiga", "Martin Sheen")# Use the reviews information above to defined defined the comments and scores vectorsscores <- c(4.6, 5, 4.8, 5, 4.2)comments <- c("I would watch it again", "Amazing!", "I liked it", "One of the best movies", "Fascinating plot")# Save the average of the scores vector as avg_reviewavg_review <- mean(scores)# Combine scores and comments into the reviews_df data framereviews_df <- data.frame(scores, comments)# Create and print out a list, called departed_list, which contains movie_title, movie_actors, reviews_df, and avg_reviewdeparted_list <- list (movie_title, movie_actors, reviews_df, avg_review)departed_list
All images, unless specified, are owned by the author. The banner image was created using Canva.