Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to delete specific rows conditionnaly for many variables in a simple way?

Let’s say I have this dataframe (but imagine it with hundreds of variables x, y, etc.).

df = data.frame ( x = c(1,2,3,4,5), y = c(1,2,3,4,5))

and I wish to delete the rows that contain either 1 or 5 in any variable.

I am familiar with the following algorithm:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df[!(df$x==1|df$x==5|df$y==1|df$y==5),]

But I am looking for a small function that can handle hundreds of variables at the same time.

>Solution :

You could use the following code:

df = data.frame ( x = c(1,2,3,4,5), y = c(1,2,3,4,5))
df[rowSums(df==1|df==5)==0,]
#>   x y
#> 2 2 2
#> 3 3 3
#> 4 4 4

Created on 2022-10-07 with reprex v2.0.2


df = data.frame ( x = c(1,2,3,4,5), y = c(1,2,3,4,5))
df[rowSums(df[-1]==1|df[-1]==5)==0,]
#>   x y
#> 2 2 2
#> 3 3 3
#> 4 4 4

Created on 2022-10-07 with reprex v2.0.2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading