How to hide NA values in an R matrix?


The hiding of NA values does not mean removal of NA values. If we have some NA values in an R matrix then we can hide them using blanks with double quotes. For example, suppose we have a matrix called M that contains some NA values then M can be printed by hiding NA value using print.table(M,na.print="")

Example

 Live Demo

M1<-matrix(sample(c(NA,rpois(2,5)),25,replace=TRUE),nrow=5)
M1

Output

    [,1] [,2] [,3] [,4] [,5]
[1,]  3    6    3    3    NA
[2,]  6    6    6    NA   3
[3,]  NA   6    6    6    3
[4,]  3    6    3    6    3
[5,]  6    3    3    3    6

Example

print.table(M1,na.print="")

Output

     [,1] [,2] [,3] [,4] [,5]
[1,]  3     6   3    3
[2,]  6    6    6         3
[3,]       6    6    6    3
[4,]  3    6    3    6    3
[5,]  6    3    3    3    6

Example

 Live Demo

M2<-matrix(sample(c(NA,rpois(2,5)),40,replace=TRUE),nrow=20)
M2

Output

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

Example

print.table(M2,na.print="")

Output

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

Example

 Live Demo

M3<-matrix(sample(c(NA,rnorm(5)),40,replace=TRUE),nrow=20)
M3

Output

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

Example

print.table(M3,na.print="")

Output

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

Updated on: 10-Feb-2021

152 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements