# Matrices in R Tutorial

Learn all about R's matrix, naming rows and columns, accessing elements also with computation like addition, subtraction, multiplication, and division.
May 2020  · 7 min read

Matrices are the objects which are elements are represented in a two-dimensional structure where mostly the numeric elements are present for doing various computation.

For example, let's look at the matrix below.

``````      [,1] [,2] [,3]
[1,]    5    6    7
[2,]    8    9   10
[3,]   11   12   13
``````

The above matrix shows that there are 3 rows and 3 columns.

In R matrix can be created using 'matrix()'.

The following way can define the syntax of a matrix in R:

``````matrix(value, nrow, ncol, byrow, dimnames)
``````

The above parameter for the matrix are defined below:

1. value - specifies the vector input, which is each entry specifies the elements in a matrix.
2. nrow - specifies the size of the row in the matrix.
3. ncol - specifies the size of the column in the matrix.
4. byrow - The boolean value consists of either TRUE or FALSE. If TRUE, the elements of the matrix are arranged in the row, whereas FALSE will arrange the element by column-wise.
5. dimnames - specifies the name given to each element of rows and columns of a matrix.

Let's see an example below where 'mat' is the name of a matrix with vector input inside c consisting of values as 8,4,5,6,7,9. It also contains the number of rows, i.e., 'nrow' as two and 'ncol' as three, which means the dimension of the matrix is 2 * 3. Also, the elements of the matrix are arranged by row, which means the entry of vector input is filled up row-wise.

``````mat = matrix(c(8,4,5,6,7,9),nrow = 2, ncol = 3,byrow = TRUE)
print(mat)
``````

The output of the above code is shown below, where there are three columns and two rows where the elements are filled up with row-wise.

``````      [,1]  [,2] [,3]
[1,]    8    4    5
[2,]    6    7    9
``````

### Naming Rows and Columns

Let's create a matrix where there are elements from 1 to 9, with the number of rows to be 3. Also, the rows and columns are named with the vector input containing a list from r1 to r3 and c1 to c3.

``````mat <- matrix(1:9,  nrow = 3,dimnames = list(c("r1","r2","r3"), c("c1","c2","c3")))
mat
``````
``````    c1    c2    c3
r1    1    4    7
r2    2    5    8
r3    3    6    9
``````

The above output shows that there are elements from 1 to 9 filled through column-wise. Also, the rows and columns are seen by labeling from r1 to r3 and c1 to c3.

## Accessing Elements in a matrix

The below matrix is named as 'mat', where it consists of 3 rows and 3 columns.

``````    c1    c2    c3
r1    1    4    7
r2    2    5    8
r3    3    6    9
``````

For accessing the above elements of a matrix individually, you need to pass a matrix name with a bracket consisting of rows and columns inside.

• To access element 5 from the above matrix following syntax is used.
`mat[2,2]`
• To access element 6 from the above matrix following syntax is used.
`mat[3,2]`
• To access all the first column of the matrix, i.e., [1 2 3] following syntax is used.
`mat[,1]`
• To access all the second row of the matrix, i.e., [2 5 8] following syntax is used.
`mat[2,]`

## Computation in the matrices

Condition: The condition for matrix addition and subtraction is the matrices need to have the same dimension where the number of rows and columns need to be identical. For example

The below matrices mat1 and mat2 consist of dimension 3 * 3, where there are 3 rows and columns where the row number and column number in both matrices are equal.

``````mat1 <- matrix(c(5,10,15,20,25,30,35,40,45), nrow = 3)
print(mat1)

mat2 <- matrix(c(50,55,60,65,70,75,80,85,90), nrow = 3)
print(mat2)
``````
``````     [,1] [,2] [,3]
[1,]    5   20   35
[2,]   10   25   40
[3,]   15   30   45
[,1] [,2] [,3]
[1,]   50   65   80
[2,]   55   70   85
[3,]   60   75   90
``````

The above matrices are printed out where each entry or elements are printed out where the entries are filled by column-wise.

``````add_output <- mat1 + mat2

sub_output <- mat1 - mat2
cat("Subtraction","\n")
print(sub_output)
``````
``````Addition
[,1] [,2] [,3]
[1,]   55   85  115
[2,]   65   95  125
[3,]   75  105  135
Subtraction
[,1] [,2] [,3]
[1,]  -45  -45  -45
[2,]  -45  -45  -45
[3,]  -45  -45  -45
``````

The above output from matrix addition and subtraction is carried where each element of both matrices get added or subtracted. For example, in matrix addition, above the entries with row 1 and column 1, which is 5 in the mat1, gets added to the entries with row 1 and column 1 in the mat2. As a result of it gets output 55. Similarly, all the entries follow a similar process in addition and subtraction to get the above result.

### Matrix Multiplication and Division

Condition: The condition for matrix multiplication and division is the number of rows and columns need to be similar. In other words, the dimension needs to be equal.

#### Matrix Multiplication

Let's see an example below where two matrices named as mat1 and mat2 are taken where a number of rows as three and columns as two are the same. There are six elements in matrices filled in column-wise, and the dimension of each matrix is 3 * 2.

``````mat1<- matrix(c(2,4,6,8,10,12), nrow = 3,ncol =2)
print(mat1)

mat2 <- matrix(c(14,16,18,20,22,24), nrow = 3,ncol=2)
print(mat2)

final <- mat1 * mat2
print('------------------')
cat("Multiplication","\n")
print(final)
``````
``````     [,1] [,2]
[1,]    2    8
[2,]    4   10
[3,]    6   12
[,1] [,2]
[1,]   14   20
[2,]   16   22
[3,]   18   24
-----------------
Multiplication
[,1] [,2]
[1,]   28  160
[2,]   64  220
[3,]  108  288
``````

The output from matrix multiplication above shows that each element from mat1 and mat2 are multiplied with each other. For example, 'mat1[1][1]', which is 2 gets multiplied to 'mat2[1][1]', which is 14, to get the result as 28. Similarly, the process is followed for every element in both matrices and finally in 'mat1[3][2]', which is 12 and mat2[3][2]' which is 24 to get the result as 288.

#### Matrix Division

Let's see an example below where two matrices named as mat1 and mat2 are taken where a number of rows as three and columns as two are the same. There are six elements in matrices filled in column-wise, and the dimension of each matrix is 3 * 2.

``````mat1<- matrix(c(2,4,6,8,10,12), nrow = 3,ncol =2)
print(mat1)

mat2 <- matrix(c(14,16,18,20,22,24), nrow = 3,ncol=2)
print(mat2)
final <- mat1 / mat2
print('--------------')
cat("Division","\n")
print(final)
``````
``````   [,1] [,2]
[1,]    2    8
[2,]    4   10
[3,]    6   12
[,1] [,2]
[1,]   14   20
[2,]   16   22
[3,]   18   24
--------------
Division
[,1]      [,2]
[1,] 0.1428571 0.4000000
[2,] 0.2500000 0.4545455
[3,] 0.3333333 0.5000000
``````

The output from the matrix division above shows that each element from mat1 and mat2 are divided with each other. For example, 'mat1[1][1]', which is two gets divided by 'mat2[1][1]', which is 14 , to get the result as 0.1428571. Similarly, the process is followed for every element in both matrices and finally in 'mat1[3][2]', which is 12 and mat2[3][2]' which is 24 to get the result as 0.5000000.

## Congratulations

Congratulations, you have made it to the end of this tutorial!

In this tutorial, you'll learn all about R's matrix, naming rows and columns, accessing elements also with computation like addition, subtraction, multiplication, and division.

### Introduction to R

Beginner
4 hours
2,395,576
Master the basics of data analysis in R, including vectors, lists, and data frames, and practice R with real data sets.
See Details

### Intermediate R

Beginner
6 hours
532,072
Continue your journey to becoming an R ninja by learning about conditional statements, loops, and vector functions.

### Introduction to Importing Data in R

Beginner
3 hours
168,703
In this course, you will learn to read CSV, XLS, and text files in R using tools like readxl and data.table.
See all courses
Related

### How to Become a Data Scientist in 8 Steps

Find out everything you need to know about becoming a data scientist, and find out whether it’s the right career for you!

12 min

### Predicting FIFA World Cup Qatar 2022 Winners

Learn to use Elo ratings to quantify national soccer team performance, and see how the model can be used to predict the winner of FIFA World Cup Qatar 2022.

Arne Warnke

### How Data Science is Changing Soccer

With the Fifa 2022 World Cup upon us, learn about the most widely used data science use-cases in soccer.

Richie Cotton

### Regular Expressions Cheat Sheet

Regular expressions (regex or regexp) are a pattern of characters that describe an amount of text. Regular expressions are one of the most widely used tools in natural language processing and allow you to supercharge common text data manipulation tasks. Use this cheat sheet as a handy reminder when working with regular expressions.

DataCamp Team

### ggplot2 Cheat Sheet

ggplot2 is considered to be one of the most robust data visualization packages in any programming language. Use this cheat sheet to guide your ggplot2 learning journey.

DataCamp Team

### A Guide to R Regular Expressions

Explore regular expressions in R, why they're important, the tools and functions to work with them, common regex patterns, and how to use them.

Elena Kosourova

16 min

See MoreSee More