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



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

  • First of all, create a data frame.

  • 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 −

x<-rpois(25,2) y<-rpois(25,5) z<-rpois(25,10) df<-data.frame(x,y,z) df

Output

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

 x y z 1 7 5 10 2 3 5 8 3 1 6 10 4 2 3 14 5 3 4 8 6 1 7 6 7 1 4 14 8 1 2 8 9 0 6 18 10 3 10 9 11 2 6 10 12 2 5 16 13 1 9 10 14 2 5 7 15 1 6 12 16 1 9 8 17 3 11 13 18 1 4 9 19 2 5 10 20 3 5 8 21 0 4 11 22 0 6 3 23 3 8 10 24 0 5 7 25 0 7 6

Remove rows that contains a specific number

Using single square subsetting with apply function to remove rows that contains 5 in data frame df −

x<-rpois(25,2) y<-rpois(25,5) z<-rpois(25,10) df<-data.frame(x,y,z) df[!apply(df==5,1,any),]

Output

 x y z 1 1 3 12 2 1 6 7 3 2 3 17 4 3 4 12 6 3 7 7 8 0 3 14 9 4 6 12 10 0 1 10 12 1 4 12 13 2 0 8 14 1 6 7 15 3 7 11 16 2 9 10 17 2 7 7 18 1 3 7 22 2 7 10 23 2 7 6 24 0 6 9 25 6 4 16
Updated on: 2021-11-11T07:03:45+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements