Naming a matrix
To help you remember what is stored in star_wars_matrix
, you would like to add the names of the movies for the rows. Not only does this help you to read the data, but it is also useful to select certain elements from the matrix.
Similar to vectors, you can add names for the rows and the columns of a matrix
rownames(my_matrix) <- row_names_vector
colnames(my_matrix) <- col_names_vector
We went ahead and prepared two vectors for you: region
, and titles
. You will need these vectors to name the columns and rows of star_wars_matrix
, respectively.
This is a part of the course
“Introduction to R”
Exercise instructions
- Use
colnames()
to name the columns ofstar_wars_matrix
with theregion
vector. - Use
rownames()
to name the rows ofstar_wars_matrix
with thetitles
vector. - Print out
star_wars_matrix
to see the result of your work.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Box office Star Wars (in millions!)
new_hope <- c(460.998, 314.4)
empire_strikes <- c(290.475, 247.900)
return_jedi <- c(309.306, 165.8)
# Construct matrix
star_wars_matrix <- matrix(c(new_hope, empire_strikes, return_jedi), nrow = 3, byrow = TRUE)
# Vectors region and titles, used for naming
region <- c("US", "non-US")
titles <- c("A New Hope", "The Empire Strikes Back", "Return of the Jedi")
# Name the columns with region
# Name the rows with titles
# Print out star_wars_matrix
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.
In this chapter, you will learn how to work with matrices in R. By the end of the chapter, you will be able to create matrices and understand how to do basic computations with them. You will analyze the box office numbers of the Star Wars movies and learn how to use matrices in R. May the force be with you!
Exercise 1: What's a matrix?Exercise 2: Analyze matrices, you shallExercise 3: Naming a matrixExercise 4: Calculating the worldwide box officeExercise 5: Adding a column for the Worldwide box officeExercise 6: Adding a rowExercise 7: The total box office revenue for the entire sagaExercise 8: Selection of matrix elementsExercise 9: A little arithmetic with matricesExercise 10: A little arithmetic with matrices (2)What is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.