How to remove rows that contain NAs in R matrix?

R ProgrammingServer Side ProgrammingProgramming

To remove rows that contain NAs in R matrix, we can follow the below steps −

  • First of all, create a matrix.

  • Then, use na.omit function to remove rows that contains NAs.

Example

Create the matrix

Let’s create a matrix as shown below −

M<-matrix(sample(c(NA,rpois(10,5)),100,replace=TRUE),ncol=4)
M

Output

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

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

Remove rows that contains NAs

Using na.omit function to remove rows that contains NAs in matrix M −

M<-matrix(sample(c(NA,rpois(10,5)),100,replace=TRUE),ncol=4)
M<-na.omit(M)
M

Output

    [,1] [,2] [,3] [,4]
[1,]  4   4    4    6
[2,]  4   3    4    3
[3,]  4   4    4    4
[4,]  4   4    4    4
[5,]  4   4    4    6
[6,]  4   4    2    4
[7,]  2   4    4    4
[8,]  2   6    3    4
[9,]  2   4    3    4
[10,] 4   2    4    4
[11,] 4   4    4    4
[12,] 4   4    4    4
[13,] 4   6    2    2
[14,] 3   4    2    4
[15,] 4   4    4    6
attr(,"na.action")
[1] 8 12 15 25 2 24 11 19 1 14
attr(,"class")
[1] "omit"
raja
Published on 15-Nov-2021 10:25:23
Advertisements