How to delete matrix rows if a particular column value satisfies some condition in R?


To delete matrix rows if a particular column satisfies some condition, we can use subsetting with single square brackets and take the subset of the matrix based on the condition. For example, if we have a matrix M and want to delete rows if column first of M do not contain value 5 then we can use the command M[M[,1]==5,].

Example

Consider the below matrix −

 Live Demo

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

Output

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

Deleting rows of M1 if first value does not contain 2 −

Example

M1[M1[,1]==2,]

Output

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

Example

 Live Demo

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

Output

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

Deleting rows of M2 if first value contain 0 −

Example

M2[M2[,1]!=0,]

Output

    [,1] [,2] [,3] [,4]
[1,]  5    0    3    0
[2,]  1    0    0    1
[3,]  1    1    2    1
[4,]  2    2    1    0
[5,]  1    0    2    0
[6,]  1    0    3    1
[7,]  1    1    0    0
[8,]  2    0    3    1
[9,]  1    0    1    1
[10,] 2    2    0    1
[11,] 1    0    0    2
[12,] 1    1    5    0
[13,] 2    2    2    0

Updated on: 17-Mar-2021

617 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements