Creating a named list
Well done, you're on a roll!
Just like on your to-do list, you want to avoid not knowing or remembering what the components of your list stand for. That is why you should give names to them:
my_list <- list(name1 = your_comp1,
name2 = your_comp2)
This creates a list with components that are named name1
, name2
, and so on. If you want to name your lists after you've created them, you can use the names()
function as you did with vectors. The following commands are fully equivalent to the assignment above:
my_list <- list(your_comp1, your_comp2)
names(my_list) <- c("name1", "name2")
This is a part of the course
“Introduction to R”
Exercise instructions
- Change the code of the previous exercise (see editor) by adding names to the components. Use for
my_vector
the namevec
, formy_matrix
the namemat
and formy_df
the namedf
. - Print out
my_list
so you can inspect the output.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Vector with numerics from 1 up to 10
my_vector <- 1:10
# Matrix with numerics from 1 up to 9
my_matrix <- matrix(1:9, ncol = 3)
# First 10 elements of the built-in data frame mtcars
my_df <- mtcars[1:10,]
# Adapt list() call to give the components names
my_list <- list(my_vector, my_matrix, my_df)
# Print out my_list
This exercise is part of the course
Introduction to R
Master the basics of data analysis in R, including vectors, lists, and data frames, and practice R with real data sets.
As opposed to vectors, lists can hold components of different types, just as your to-do lists can contain different categories of tasks. This chapter will teach you how to create, name, and subset these lists.
Exercise 1: Lists, why would you need them?Exercise 2: Lists, why would you need them? (2)Exercise 3: Creating a listExercise 4: Creating a named listExercise 5: Creating a named list (2)Exercise 6: Selecting elements from a listExercise 7: Creating a new list for another movieWhat is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.