How to replace matrix values using if else in R?


To replace matrix values using ifelse in R, we can follow the below steps −

  • First of all, create a matrix.
  • Then, use ifelse function to replace the values in the matrix.

Create the matrix

Let’s create a matrix as shown below −

 Live Demo

M<-matrix(rpois(80,2),ncol=4)
M

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

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

Replace values in the matrix using if else

Using if else function to replace 3 in matrix M with 1 −

 Live Demo

M<-matrix(rpois(80,2),ncol=4)
ifelse(M==3,1,M)

Output

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

Updated on: 13-Aug-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements