Get Started

Selection of matrix elements

Similar to vectors, you can use the square brackets [ ] to select one or multiple elements from a matrix. Whereas vectors have one dimension, matrices have two dimensions. You should therefore use a comma to separate the rows you want to select from the columns. For example:

  • my_matrix[1,2] selects the element at the first row and second column.
  • my_matrix[1:3,2:4] results in a matrix with the data on the rows 1, 2, 3 and columns 2, 3, 4.

If you want to select all elements of a row or a column, no number is needed before or after the comma, respectively:

  • my_matrix[,1] selects all elements of the first column.
  • my_matrix[1,] selects all elements of the first row.

Back to Star Wars with this newly acquired knowledge! As in the previous exercise, all_wars_matrix is already available in your workspace.

This is a part of the course

“Introduction to R”

View Course

Exercise instructions

  • Select the non-US revenue for all movies (the entire second column of all_wars_matrix), store the result as non_us_all.
  • Use mean() on non_us_all to calculate the average non-US revenue for all movies. Simply print out the result.
  • This time, select the non-US revenue for the first two movies in all_wars_matrix. Store the result as non_us_some.
  • Use mean() again to print out the average of the values in non_us_some.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# all_wars_matrix is available in your workspace
all_wars_matrix

# Select the non-US revenue for all movies
non_us_all <- 
  
# Average non-US revenue

  
# Select the non-US revenue for first two movies
non_us_some <- 
  
# Average non-US revenue for first two movies
Edit and Run Code

This exercise is part of the course

Introduction to R

BeginnerSkill Level
4.7+
598 reviews

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 elements
Exercise 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.

Start Learning for Free