How to subset a matrix in R by specifying columns that contains NA?

R ProgrammingServer Side ProgrammingProgramming

To subset a matrix in R by specifying columns that contains NA, we can follow the below steps −

  • First of all, create a matrix with some NAs.

  • Then, use is.na along with subset function to subset the matrix by specifying columns that contains NA.

Example

Create the matrix

Let’s create a matrix as shown below −

M<-matrix(sample(c(NA,round(rnorm(3),2)),75,replace=TRUE),ncol=3)
M

Output

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

      [,1]   [,2]  [,3]
[1,]   NA   -0.05  1.93
[2,]  -1.31 -1.31 -0.05
[3,]  -0.05 -0.05  NA
[4,]   NA    1.93 -1.31
[5,]  -0.05 -0.05 -0.05
[6,]   NA   -1.31  NA
[7,]  -1.31 -0.05  1.93
[8,]   1.93  1.93  NA
[9,]  -1.31 -1.31 -1.31
[10,]  NA    1.93  NA
[11,] -0.05 -1.31  1.93
[12,] -1.31 -0.05 -0.05
[13,]  NA    1.93 -1.31
[14,]  NA    NA   -0.05
[15,]  NA   -0.05  NA
[16,] -0.05 -1.31 -1.31
[17,]  1.93 -0.05 -0.05
[18,] -0.05 -0.05  NA
[19,] -0.05 -0.05  1.93
[20,] -0.05  1.93 -1.31
[21,] -0.05 -1.31 -0.05
[22,] -1.31 -0.05  NA
[23,] -0.05  1.93  1.93
[24,]  NA   -1.31 -1.31
[25,] -0.05  1.93 -1.31

Subset matrix by specifying columns having NAs

Using is.na along with subset function to subset the matrix M by specifying columns 1 and 3 that contains NA as shown below −

M<-matrix(sample(c(NA,round(rnorm(3),2)),75,replace=TRUE),ncol=3)
subset(M,is.na(M[,1])|is.na(M[,3]))

Output

     [,1]   [,2]  [,3]
[1,]   NA   -0.05  1.93
[2,]  -0.05 -0.05  NA
[3,]   NA    1.93 -1.31
[4,]   NA   -1.31  NA
[5,]   1.93  1.93  NA
[6,]   NA    1.93  NA
[7,]   NA    1.93 -1.31
[8,]   NA    NA   -0.05
[9,]   NA   -0.05  NA
[10,] -0.05 -0.05  NA
[11,] -1.31 -0.05  NA
[12,]  NA   -1.31 -1.31
raja
Published on 16-Nov-2021 06:41:17
Advertisements