How to replace 0 with NA in an R matrix?

R ProgrammingServer Side ProgrammingProgramming

To replace 0 with NA in an R matrix, we can use subsetting with single square brackets and then set zeros to NA.

For Example, if we have a matrix called M that contains some zeros then we can replace 0 with NA by using the command mentioned below −

M[M==0]<-NA

Example 1

Consider the matrix given below −

M1<-matrix(rpois(80,1),ncol=4)
M1

The following dataframe is created

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

To replace 0 in M1 with NA on the above created data frame, add the following code to the above snippet −

M1<-matrix(rpois(80,1),ncol=4)
M1[M1==0]<-NA
M1

Output

If you execute all the above given snippets as a single program, it generates the following Output −

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

Example 2

Consider the matrix given below −

M2<-matrix(round(rnorm(60),0),ncol=3)
M2

The following dataframe is created

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

To replace 0 in M2 with NA on the above created data frame, add the following code to the above snippet −

M2<-matrix(round(rnorm(60),0),ncol=3)
M2[M2==0]<-NA
M2

Output

If you execute all the above given snippets as a single program, it generates the following Output −


     [,1] [,2] [,3]
[1,]   1   NA    1
[2,]  -1   NA   -1
[3,]  -2   -1    1
[4,]  -1   -1   NA
[5,]  -1    1    1
[6,]  -2   NA   NA
[7,]  -1   NA   NA
[8,]  NA   NA   NA
[9,]   1   NA   NA
[10,] NA   NA   -1
[11,] NA    1   -1
[12,] -1   -1   -2
[13,] -1   NA   -1
[14,] -1   -1    1
[15,] NA   -1   NA
[16,]  1   NA    2
[17,] NA    1    1
[18,] NA   NA   NA
[19,] NA    1    1
[20,] -2   -1   -1
raja
Published on 01-Nov-2021 07:39:43

Advertisements