How to replace the values in a matrix with another value based on a condition in R?


A matrix has only numeric values and sometimes these values are either incorrectly entered or we might want to replace some of the values in a matrix based on some conditions. For example, if we have few fives in a matrix then we might want to replace all fives to an another number which is greater than 5 or less than 5.

Example

Consider the below matrix −

set.seed(123)
M <-matrix(sample(1:50,25),nrow=5)
M

Output

  [,1] [,2] [,3] [,4] [,5]
[1,] 31 43 27 29 36
[2,] 15 37 5 8 19
[3,] 14 48 40 41 4
[4,] 3 25 28 7 45
[5,] 42 26 9 10 17

Replacing values based on different conditions −

Example

M[M <5]<-10
M

Output

[,1] [,2] [,3] [,4] [,5]
[1,] 31 43 27 29 36
[2,] 15 37 5 8 19
[3,] 14 48 40 41 10
[4,] 10 25 28 7 45
[5,] 42 26 9 10 17

Example

M[M=5] <-15
M

Output

  [,1] [,2] [,3] [,4] [,5]
[1,] 31 43 27 29 36
[2,] 15 37 5 8 19
[3,] 14 48 40 41 10
[4,] 10 25 28 7 45
[5,] 15 26 9 10 17

prettyprint

M[M==5] <-15
M

Output

  [,1] [,2] [,3] [,4] [,5]
[1,] 31 43 27 29 36
[2,] 15 37 15 8 19
[3,] 14 48 40 41 10
[4,] 10 25 28 7 45
[5,] 15 26 9 10 17

Example

M[M<10&M>5]<-21
M

Output

[,1] [,2] [,3] [,4] [,5]
[1,] 31 43 27 29 36
[2,] 15 37 15 21 19
[3,] 14 48 40 41 10
[4,] 10 25 28 21 45
[5,] 15 26 21 10 17

Example

M[M >30]<-25
M

Output

[,1] [,2] [,3] [,4] [,5]
[1,] 25 25 27 29 25
[2,] 15 25 15 21 19
[3,] 14 25 25 25 10
[4,] 10 25 28 21 25
[5,] 15 26 21 10 17

Example

M[M==14] <-25
M

Output

[,1] [,2] [,3] [,4] [,5]
[1,] 25 25 27 29 25
[2,] 15 25 15 21 19
[3,] 25 25 25 25 10
[4,] 10 25 28 21 25
[5,] 15 26 21 10 17

Example

M[M==17] <-15
M

Output

[,1] [,2] [,3] [,4] [,5]
[1,] 25 25 27 29 25
[2,] 15 25 15 21 19
[3,] 25 25 25 25 10
[4,] 10 25 28 21 25
[5,] 15 26 21 10 15

Example

M[M>25&M <30]<-25
M

Output

[,1] [,2] [,3] [,4] [,5]
[1,] 25 25 25 25 25
[2,] 15 25 15 21 19
[3,] 25 25 25 25 10
[4,] 10 25 25 21 25
[5,] 15 25 21 10 15

Updated on: 21-Aug-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements