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

R – Remove all row that only have NA

I have this type of dataset with ID, age and gender and then questions the ID’s have responded in a survey:

> ID gender age Q1 Q2 Q3
  1  male   35  1  1   NA
  2  male   45  NA NA  NA
  3 female  55  NA NA  NA

I want to remove all rows where all Q´s is NA, so in this case the result will be:

> ID gender age Q1 Q2 Q3
  1  male   35  1  1   NA

How can I do so with data.table?

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

>Solution :

library(tidyverse)

df %>%
  filter(if_any(starts_with("Q"), ~ !is.na(.x)))

# A tibble: 1 × 6
     ID gender   age    Q1    Q2 Q3   
  <dbl> <chr>  <dbl> <dbl> <dbl> <lgl>
1     1 male      35     1     1 NA   
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