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

Remove groups if all NA

Let’s say I have a table like so:

df <- data.frame("Group" = c("A","A","A","B","B","B","C","C","C"),
              "Num" = c(1,2,3,1,2,NA,NA,NA,NA))

  Group Num
1     A   1
2     A   2
3     A   3
4     B   1
5     B   2
6     B  NA
7     C  NA
8     C  NA
9     C  NA

In this case, because group C has Num as NA for all entries, I would like to remove rows in group C from the table. Any help is appreciated!

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 :

You could group_by on you Group and filter the groups with all values that are NA. You can use the following code:

library(dplyr)
df %>%
  group_by(Group) %>%
  filter(!all(is.na(Num)))
#> # A tibble: 6 × 2
#> # Groups:   Group [2]
#>   Group   Num
#>   <chr> <dbl>
#> 1 A         1
#> 2 A         2
#> 3 A         3
#> 4 B         1
#> 5 B         2
#> 6 B        NA

Created on 2023-01-18 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