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

Selecting rows based on condition in R and keep rows with missing values

I have a dataframe in R (dd_sub) with a column (E) and want to drop the rows where E > 0.
The column has rows where E = "NA" , E < 0 and E > 0.

When I write this :

dd_subset <- dd_sub[ which( dd_sub$E < 0 | dd_sub$E == "NA"), ]

I only get the row where E < 0.

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

Is there a way to solve this?
Thank you

>Solution :

You don’t need to use which(). You can just declare the condition – which returns a logical array – so the rows whose position is TRUE in the condition are selected.

Also, dd_sub$E == "NA" match a string ‘NA’, not the definition of missing value. is.na() returns TRUE in the positions where the value is missing.

dd_subset <- dd_sub[dd_sub$E < 0 | is.na(dd_sub$E), ]

Other possibility is to write the negative – with ! – of the rows you want to drop.

dd_subset <- dd_sub[! dd_sub$E >= 0]
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