How to remove rows in R matrix that contains a specific number?


To remove rows in R matrix that contains a specific number, we can follow the below steps −

  • First of all, create a matrix.

  • Then, use single square subsetting with apply function to remove rows that contains a specific number.

Example

Create the data frame

Let’s create a data frame as shown below −

M<-matrix(sample(1:25,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,]   2   16  6    22
[2,]  21   8   2     1
[3,]   9   3   1     4
[4,]   8  22   4    25
[5,]  25  19  24    21
[6,]  20  16   5     2
[7,]   1  21   3     5
[8,]  23  5   15     2
[9,]  12  5   2     11
[10,]  9 20  15      3
[11,] 18 14  11      6
[12,] 18 12   7      5
[13,] 24  3  19      9
[14,] 24 22  20     16
[15,] 15 20  18      5
[16,] 13 11   9     17
[17,]  4 22   4     17
[18,] 14 25   8     18
[19,] 12  3  17     24
[20,] 20 18   7     23
[21,]  3 17  20      5
[22,]  3 13  14     18
[23,] 20 15  21      9
[24,]  5  7   6      2
[25,]  9  2   7     10

Remove rows that contains a specific number

Using single square subsetting with apply function to remove rows that contains 20 in matrix M −

M<-matrix(sample(1:25,100,replace=TRUE),ncol=4)
M[!apply(M==20,1,any),]

Output

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

Updated on: 11-Nov-2021

406 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements