HomeTutorialsR Programming

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.

Topics

R Courses

Course

.css-1531qan{-webkit-text-decoration:none;text-decoration:none;color:inherit;}Introduction to R

4 hr
2.7M
Master the basics of data analysis in R, including vectors, lists, and data frames, and practice R with real data sets.
See Details
Start Course

Course

Intermediate R

6 hr
598.6K
Continue your journey to becoming an R ninja by learning about conditional statements, loops, and vector functions.

Course

Writing Efficient R Code

4 hr
47.2K
Learn to write faster R code, discover benchmarking and profiling, and unlock the secrets of parallel programming.
See More
Related

blog

R Correlation Tutorial

Get introduced to the basics of correlation in R: learn more about correlation coefficients, correlation matrices, plotting correlations, etc.

David Woods

18 min

tutorial

Arrays in R

Learn about Arrays in R, including indexing with examples, along with the creation and addition of matrices and the apply() function.

Olivia Smith

8 min

tutorial

Understanding Confusion Matrix in R

This tutorial takes course material from DataCamp's Machine Learning Toolbox course and allows you to practice confusion matrices in R.

Ryan Sheehy

3 min

tutorial

Introduction to Data frames in R

This tutorial takes course material from DataCamp's Introduction to R course and allows you to practice data frames.

Ryan Sheehy

5 min

tutorial

Data Types in R

Learn about data types and their importance in a programming language. More specifically, learn how to use various data types like vector, matrices, lists, and dataframes in the R programming language.

12 min

tutorial

Operators in R

Learn how to use arithmetic and logical operators in R. These binary operators work on vectors, matrices, and scalars.

DataCamp Team

4 min

See MoreSee More