How to Create & Access R Matrix – 5 Operations That You Must Check

A matrix in R is a two-dimensional rectangular data set and thus it can be created using vector input to the matrix function. R is a tool for expressing statistical and mathematical operations. For which beginners should know how to create and access the R matrix. By the end of this article, you can perform addition, subtraction, multiplication, and division operations on R Matrices.

Learn R Matrix

1. What is R Matrix?

A matrix is a collection of numbers arranged into a fixed number of rows and columns. Usually, the numbers are the real numbers. By using a matrix function we can reproduce a memory representation of the matrix in R.

Hence, the data elements must be of the same basic type.

Before diving into R matrix, Brush up your skills for Vectors in R

A = matrix (
c(2 , 4, 3, 1, 5, 7)       # the data elements
nrow =2,                   # no. of rows
ncol =3,                   # no. of columns
byrow = TRUE)

R matrix Example

An element at the mth row, the nth column of our matrix ‘mat’ can be using this expression mat[m, n]

mat[2, 3]

To extract only the mth row of our matrix mat, we can use this expression mat[m, ]

mat[2, ]

And, to only extract the nth column of our matrix mat, we use this expression mat[, n]

mat[ ,3]

How to access R Matrix

Recommended Reading – Array Functions in R 

2. History of Matrices in R

The history of matrices goes back to ancient times! But the matrix was not applied to the concept till 1850.

“Matrix” is the Latin word for womb. It can also mean more generally any place in which something formed or produced. The word has used in unusual ways by at least two authors of historical importance. They proposed this axiom as a means to reduce any function to one of the lower types so that at the “bottom” (0order) the function is identical to its extension.

By using the process of Generalization any possible function other than a matrix derived from a matrix that is, by considering the proposition which asserts that the function in question is true with all possible values or with some value of one of the arguments, the other argument or arguments remaining undetermined”.

3. How to Create Matrix in R?

In order to create our first matrix in R, we will use the matrix() function. The basic syntax for creating a matrix in R is as follows:

matrix(data, nrow, ncol, byrow, dimnames)

Where,

  1. Data is the input vector. This can also include a list or an expression.
  2. Nrow is the number of rows that we wish to create in our matrix
  3. Ncol is the specification of the number of columns in our matrix.
  4. Byrow is a logical attribute which is FALSE by default. Setting it true will arrange the input vectors by row.
  5. Dimnames allows you to name rows and columns in a matrix.

3.1 Creating R matrix based on the variations in the attributes

3.1.1 Creating R matrix by arranging the elements sequentially by row

arrang_row <- matrix(c(4:15), nrow = 4, byrow = TRUE) #Creating our matrix and arranging it by row
print(arrang_row) #Printing our arranged matrix

In the above code, we specified the range for our array from 4 to 15 in the c() function. We specified the number of rows as 4 and arranged the elements sequentially.

 R matrix by arranging elements by row

Struggling with Factors in R? Get a Complete guide to master it.

3.1.2 Creating R matrix by arranging elements sequentially by column

arrang_col <- matrix(c(4:15), nrow = 4, byrow = FALSE)       #Creating our matrix and arranging it by column

print(arrang_col)    #Printing our arranged matrix 

 R matrix by arranging elements by Columns

3.1.3 Defining names of columns and rows in a matrix

In order to define rows and column names, you can create two vectors of names, one for row and other for a column. Then, using the Dimnames attribute, you can name them appropriately –

rows = c("row1", "row2", "row3", "row4")     #Creating our character vector of row names

cols = c("colm1", "colm2", "colm3")          #Creating our character vector of column names

mat <- matrix(c(4:15), nrow = 4, byrow = TRUE, dimnames = list(rows, cols) )   
#creating our matrix mat and assigning our vectors to dimnames

print(mat)                    #Printing our matrix

Defining names of columns and rows in a R matrix

4. How to Access Elements of Matrix in R?

In this section, we will learn how to access elements of a Matrix in R. For this, we will use the matrix ‘mat’ that we created before. We can access the elements of this matrix ‘mat’ in the following ways –

The syntax for accessing the element at nth row of mth column of our matrix mat is – mat[n,m]

For example –

> print(mat[2,3])

Furthermore, to access only the elements of nth row, we use mat[n, ] such that

> print(mat[2, ])

And, to access only the elements of mth column, we use mat[ ,m]

> print(mat[ , 2])

How to access elements in R

Must explore the Data Frames in R, to enhance your skills.

5. How to Modify Matrix In R?

In order to modify our matrix ‘mat’ in R, there are several methods.

5.1 Assign a Single Element

The first method is to assign a single element to the position of R matrix that will modify the original value.

The basic syntax for it is mat[n,m] <- y, where n and m are the rows and columns of the element respectively. And y is the value that we assign to modify our matrix.

> mat    #Displaying values of matrix mat

> mat[2,3] <- 20  #Assigning value 20 to the element at 2nd row and 3rd column
> mat   		#Displaying our modified matrix.

Assign a single element to modify Matrix

Here, we modify ‘mat’ by replacing the value at 2nd row and 3rd column, that is, 9 with 20.

5.2 Use of Relation Operators

Another method of modifying is with the use of relational operators like >, <, ==.

> mat[mat == 4] <- 0     #Replacing elements that are equal to 4 with 0
> mat  			#Displaying our modified matrix ‘mat’

R matrix Modify by relation operators

Here, we use == operator to replace the value that is equal to 4 with 0. Similarly, we can use < operator to replace values that are less than 10 with 0 –

> mat[mat < 10] <- 0       #Replacing elements that are less with 10 with 0
> mat				#Displaying modified matrix ‘mat’

Relational operators helps to modify the R matrices

It’s right to uncover the Matrix Functions in R.

5.3 Addition of Rows and Columns

Another method of modifying a R matrix is through the addition of rows and columns using the rbind() and cbind() function respectively. For this, we create a new matrix ‘new_mat’ with 3 rows and 3 columns –

> new_mat = matrix(1:12, nrow = 3, ncol = 3)
> new_mat

Now, we will add a column to our matrix ‘new_mat’ using cbind() function as follows:

> cbind(new_mat, c(1,2,3))

We can also add a row using the rbind() function as follows –

> rbind(new_mat, c(1,2,3))

Addition of Rows and Columns

You can also modify the dimension of the matrix ‘new_mat’ using the dim() function as follows:

dim(new_mat) <- c(1,9)
new_mat

Modify R matrix with dim function

Here, you modified the original dimension of ‘new_mat’, which was 3×3 into 1×9.

Since the dimensions of our new_mat matrix have been changed, we will reverse it to 3×3 using

dim(new_mat) <- c(3,3)

You can also carry out the transpose of the matrix using the t() function

> t(new_mat)

R Matrix Transpose

Get a Free Cheat Sheet for R Data Structure

6. R Matrix Operations

There are several operations, we can perform on the R matrices to get desired results.

6.1 Addition

In order to perform addition on matrices in R, we first create two matrices ‘mat1’ and ‘mat2’ with four rows and four columns as follows:

mat1 <- matrix(data = 1:8, nrow = 4, ncol = 4) #Creating our first matrix mat1 
mat2 <- matrix(data = 1:16, nrow = 4, ncol = 4) #Creating our second matrix mat2

We will use these two matrices for all of our mathematical operations.

In order to perform addition on A and B, we simply use ‘+’ as follows:

sum <- mat1 + mat2 #Adding our two matrices
print(sum) #Printing the sum

Addition of R Matrix

6.2 Subtraction

In order to perform subtraction, we make use of ‘-’ as follows –

sub <- mat1 - mat2 #Adding our two matrices
print(sub) #Printing the sum

Subtract of Matrices in R

6.3 Matrix Multiplication (By Constant)

For multiplication with a constant, we simply take our mat1 matrix and multiply it with a constant. In this case, we multiply it by 4 –

prod <- mat1*4 #Multiplying matrix mat1 with constant value 4
print(prod) #Printing the product

Multiplication in R matrix

Do you know What is OLS Regression in R?

6.4 Multiplication

For the multiplication of two matrices, we multiply our matrices mat1 and mat2 as follows –

prod <- mat1*mat2 #Multiplying matrix mat1 with mat2
print(prod) #Printing the product

R matrix Multiplication

6.5 Division

To perform division between our matrices, we use ‘/’ as follows –

div <- mat1/mat2 #Division of mat1 and mat2 
print(div) #Printing the division

How to divide R matrix

 

Why Choose R for Data Science?

R Quiz

7. Applications of R Matrices

  • In geology, Matrices is been used for taking surveys and hence, used for plotting graphs, statistics, and studies in almost different fields.
  • To represent the real world data are like traits of people’s population. They are the best representation method for plotting common survey things.
  • In robotics and automation, matrices are the best elements for the robot movements.
  • Matrices are used in calculating the gross domestic products in economics. Therefore, it helps in calculating goods product efficiency.
  • In computer-based application, matrices play a vital role in the projection of three-dimensional image into a two-dimensional screen creating the realistic seeming motions.
  • In physical related applications, matrices can be applied in the study of an electrical circuit.

8. Conclusion

Hence, we have studied in detail about R matrices. Moreover, we learned about uses of matrices and we also called it operations which we perform on other matrices functions by using this. So, this above-mentioned information is sufficient enough to understand matrices and their uses.

Hope you find this blog on R Matrix.helpful. Still, you have any query related to R matrices so please leave a comment below.

2 Responses

  1. Rachel says:

    I still don’t understand in what cases matrices might be more useful than vectors. It seems like you can multiply, divide, etc. vectors just as easily as matrices and matrices don’t necessarily put the values in any order that the vector doesn’t? So I don’t understand the purpose of making matrices out of vectors.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.