Home » How to Replace Values in a Matrix in R (With Examples)

How to Replace Values in a Matrix in R (With Examples)

by Tutor Aspire

You can use the following methods to replace specific values in a matrix in R:

Method 1: Replace Elements Equal to Specific Value

#replace 5 with 100
my_matrix[my_matrix==5] 

Method 2: Replace Elements Based on One Condition

#replace elements with value less than 15 with 0
my_matrix[my_matrix15] 

Method 3: Replace Elements Based on Multiple Conditions

#replace elements with value between 10 and 15 with 99
my_matrix[my_matrix>=10 & my_matrix15] 

The following examples show how to use each method in practice with the following matrix in R:

#create matrix
my_matrix 5)

#display matrix
my_matrix

     [,1] [,2] [,3] [,4]
[1,]    1    6   11   16
[2,]    2    7   12   17
[3,]    3    8   13   18
[4,]    4    9   14   19
[5,]    5   10   15   20

Example 1: Replace Elements Equal to Specific Value

The following code shows how to replace all elements equal to the value 5 with the value 100:

#replace 5 with 100
my_matrix[my_matrix==5] #view updated matrix
my_matrix

     [,1] [,2] [,3] [,4]
[1,]    1    6   11   16
[2,]    2    7   12   17
[3,]    3    8   13   18
[4,]    4    9   14   19
[5,]  100   10   15   20

Notice that the one element equal to the value 5 has been replaced with a value of 100.

All other elements remained unchanged in the matrix.

Example 2: Replace Elements Based on One Condition

The following code shows how to replace all elements that have a value less than 15 with the value 0:

#replace elements with value less than 15 with 100
my_matrix[my_matrix15] #view updated matrix
my_matrix

     [,1] [,2] [,3] [,4]
[1,]    0    0    0   16
[2,]    0    0    0   17
[3,]    0    0    0   18
[4,]    0    0    0   19
[5,]    0    0   15   20

Notice that each of the elements that have a value less than 15 have been replaced with a value of 0.

Example 3: Replace Elements Based on Multiple Conditions

The following code shows how to replace all elements that have a value between 10 and 15 with a value of 99:

#replace elements with value between 10 and 15 with 99
my_matrix[my_matrix>=10 & my_matrix15] #view updated matrix
my_matrix

     [,1] [,2] [,3] [,4]
[1,]    1    6   99   16
[2,]    2    7   99   17
[3,]    3    8   99   18
[4,]    4    9   99   19
[5,]    5   99   99   20

Notice that each of the elements that have a value between 10 and 15 have been replaced with a value of 99.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Sort a Matrix in R
How to Remove NA from Matrix in R
How to Convert Data Frame to Matrix in R
How to Convert a Table to a Matrix in R

You may also like