Introduction to Matrices in R. Learn how to create matrices and... | by Linda Ngo | Towards Data Science

A matrix is a collection of elements of the same data type (numeric, character, or logical) arranged into a fixed number of rows and columns. A two-dimensional matrix is one that works only with rows and columns.
The matrix() function in R creates a matrix. Consider the following example:
matrix(1:9, byrow=TRUE, nrow = 3)
This constructs a matrix with 3 rows, containing the numbers 1 to 9, filled row-wise.
In the matrix() function:
The first argument is the collection of elements that R will arrange into the rows and columns of the matrix. Here, we used 1:9 (this is the same as c(1,2,3,4,5,6,7,8,9) (see vectors in R)). This is an optional argument and can be filled later. If we leave it blank, the matrix just won’t be filled.
The argument byrow indicates that the matrix is filled row-wise. If we want the matrix to be filled column-wise, we set this argument to FALSE (That is, byrow=FALSE ). By default, the matrix is filled by columns, byrow=FALSE .
# Row-wise  # Column-wise   1 2 3        1 4 7   4 5 6        2 5 8   7 8 9        3 6 9
The third argument nrow indicates the desired number of rows. nrows=3 indicates that the matrix should have three rows.
There are also other arguments such as:
ncol which indicates the desired number of columns.
Let’s analyze the box office numbers for the Star Wars franchise.
Below are three vectors each defining the box office numbers of one of the first three Star Wars movies. The first element of each vector indicates the US box office revenue, the second element refers to the Non-US box office (Source: Wikipedia).
# 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)
To construct a matrix from these three vectors, we will first need to combine the three vectors into one.
box_office <- c(new_hope, empire_strikes, return_jedi)
We then use the matrix() function to construct a matrix. The first argument is the vector box_office , which contains all box office figures. Next, we have to specify nrow=3 and byrow=TRUE to construct the matrix with 3 rows filled row-wise (the first column will represent the US revenue, the second non-US revenue).
star_wars_matrix <- matrix(box_office, byrow=TRUE, nrow=3)
It is often helpful to add names to the rows and columns of a matrix to help remember what is stored in it. Not only does it help with reading the data, but also with selecting certain elements from the matrix. We can achieve this by using the functions colnames() and rownames() .
rownames(my_matrix) <- row_names_vectorcolnames(my_matrix) <- col_names_vector
To name the columns by region and titles, vectors representing these names are needed.
# Vectors region and titles, used for namingregion <- c("US", "non-US")titles <- c("A New Hope", "The Empire Strikes Back", "Return of the Jedi")
To name the columns of star_wars_matrix with the region vector, colnames() must be used.
# Name the columns with regioncolnames(star_wars_matrix) <- region
To name the rows of star_wars_matrix with the titles vector, rownames() must be used.
# Name the rows with titlesrownames(star_wars_matrix) <- titles
Your code should like something like this now:
# 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 matrixstar_wars_matrix <- matrix(c(new_home, empire_strikes, return_jedi), nrow = 3, byrow = TRUE)# Vectors region and titles, used for namingregion <- c("US", "non-US")titles <- c("A New Hope", "The Empire Strikes Back", "Return of the Jedi")# Name the columns with regioncolnames(star_wars_matrix) <- region# Name the rows with titlesrownames(star_wars_matrix) <- titles# Print out star_wars_matrixstar_wars_matrix
The dimnames atrribute for the matrix can be used to name the rows and columns of the matrix. The dimnames atrribute takes a list of length 2 giving the row and column names respectively. That is,
dimnames = list(row_vector,column_vector)
So, during the construction of the matrix, we can directly label it then.
# Construct star_wars_matrixbox_office <- c(460.998, 314.4, 290.475, 247.900, 309.306, 165.8)star_wars_matrix <- matrix(box_office, nrow = 3, byrow = TRUE, dimnames = list(c("A New Hope", "The Empire Strikes Back", "Return of the Jedi"),c("US, "non-US")))
An important statistic for a movie is its worldwide box office figures. To calculate the total box office revenue for the three Star Wars movies, you need to determine the sum of the US revenue and the non-US revenue.
The function rowSums() calculates the totals for each row of a matrix and creates a new vector:
rowSums(my_matrix)
Calculate the worldwide box office figures for the three movies.
# Construct star_wars_matrixbox_office <- c(460.998, 314.4, 290.475, 247.900, 309.306, 165.8)star_wars_matrix <- matrix(box_office, nrow = 3, byrow = TRUE, dimnames = list(c("A New Hope", "The Empire Strikes Back", "Return of the Jedi"),c("US, "non-US")))# Calculate worldwide box office figuresworldwide_vector <- rowSums(star_wars_matrix)
You can add a column or multiple columns to a matrix using the cbind() function, which merges matrices and/or vectors together by column. For example:
big_matrix <- cbind(matrix1, matrix2, vector1, ...)
In the previous exercise, you calculated the vector that contained the worldwide box office revenue for each of the three movies. However, this vector is not yet part of the star_wars_matrix . Add this vector as a new column to the matrix and assign the result to a new matrix.
# Construct star_wars_matrixbox_office <- c(460.998, 314.4, 290.475, 247.900, 309.306, 165.8)star_wars_matrix <- matrix(box_office, nrow = 3, byrow = TRUE, dimnames = list(c("A New Hope", "The Empire Strikes Back", "Return of the Jedi"),c("US, "non-US")))# Calculate worldwide box office figuresworldwide_vector <- rowSums(star_wars_matrix)# Bind the new variable worldwide_vector as a column to star_wars_matrixall_wars_matrix <- cbind(star_wars_matrix, worldwide_vector)
To add a column, you can use cbind() . To add a row, you can use rbind() . The rbind() function takes a sequence of vectors or matrices arguments and combines them by row. For example,
big_matrix <- rbind(matrix1, matrix2, vector1, ...)
Similar to how you created the star_wars_matrix with data on the original trilogy, create a second matrix with similar data for the prequels trilogy.
Then use rbind() to combine the two matrices, with data for the original trilogy first then data for the prequels second.
# Construct star_wars_matrixbox_office <- c(461.0, 314.4, 290.5, 247.9, 309.3, 165.8)star_wars_matrix <- matrix(box_office, nrow = 3, byrow = TRUE, dimnames = list(c("A New Hope", "The Empire Strikes Back", "Return of the Jedi"), c("US", "non-US")))# Construct star_wars_matrix2box_office2 <- c(474.5, 552.5, 310.7, 338.7, 380.3, 468.5)star_wars_matrix2 <- matrix(box_office2, nrow = 3, byrow = TRUE, dimnames = list(c("The Phantom Menace", "Attack of the Clones", "Revenge of the Sith"), c("US", "non-US")))# Combine both Star Wars trilogies in one matrixall_wars_matrix <- rbind(star_wars_matrix, star_wars_matrix2)
Similar to how we used rowSums() to calculate the sum of each row, we can also use colSums() to calculate the sum of each column of the matrix.
rowSums(my_matrix)
Using the all_wars_matrix constructed in the previous exercise, calculate the total box office revenue for the US and the non-US region for the entire saga.
# Total revenue for US and non-UStotal_revenue_vector <- colSums(all_wars_matrix)
Similar to vectors, square brackets [] can be used to select one or multiple elements from a matrix. Since matrices are two dimensional, a comma is needed to separate the rows and columns. For example:
my_matrix[1,2] selects the element at the first row and second column (row 1, column 2)
my_matrix[1:3, 2:4] returns a matrix with the data on rows 1 through 3, and columns 2 through 4.
To select all elements of a row, no number is needed after the column. To select all elements of a column, no number is needed before the column.
my_matrix[,1] selects all elements of the first column.
my_matrix[1,] selects all elements of the first row.
Calculate the mean the non-US revenue for all movies (Hint: select the entire second column of the all_wars_matrix , and use the mean() function).
# Select the non-US revenue for all moviesnon_us_all <- all_wars_matrix# Average non-US revenuemean(non_us_all)
Calculate the mean for the first two movies of the saga.
# Select the non-US revenue for the first two moviesnon_us_some <- all_wars_matrix[1:2,2]# Average non-US revenue for the first two moviesmean(non_us_some)
The standard operators like + , - , / , * , etc. that work with vectors, work in an element-wise way on matrices as well.
For example, 2 * my_matrix multiples each element of my_matrix by 2.
You can also multiply a matrix by another matrix. For example, my_matrix1 * my_matrix2 creates a matrix where each element is the product of the corresponding elements in my_matrix1 and my_matrix2 .
Suppose the price of a movie ticket was 5 dollars. Determine how many visitors went to each movie for each geographical area. (Hint: simply dividing box office numbers by the ticket price will give you the number of visitors).
# Estimate the visitorsvisitors <- all_wars_matrix / 5
Suppose ticket prices go up over time. Given a matrix of the ticket prices, determine the estimated number of US and non-US visitors for all the movies.
# Construct ticket_prices_matrixticket_prices <- c(5.0, 5.0, 6.0, 6.0, 7.0, 7.0, 4.0, 4.0, 4.5, 4.5, 4.9, 4.9)ticket_prices_matrix <- matrix(ticket_prices, nrow = 6, byrow = TRUE, dimnames = list(c("A New Hope", "The Empire Strikes Back", "Return of the Jedi","The Phantom Menace", "Attack of the Clones", "Revenge of the Sith"),c("US", "non-US")))
# Estimated number of visitorsvisitors <- all_wars_matrix / ticket_prices_matrix
Calculate the average number of US visitors (Hint: you’ll need to have completed the second for you to try)
# US visitors (Select the entire first column)us_visitors <- visitors[,1]# Average number of US visitorsmean(us_visitors)
All images, unless specified, are owned by the author. The banner image was created using Canva.