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 filter out groups empty for 1 column in Tidyverse

tibble(
  A = c("A","A","B","B"),
  x = c(NA,NA,NA,1),
  y = c(1,2,3,4),
) %>% group_by(A) -> df

desired output:

tibble(
  A = c("B","B"),
  x = c(NA,1)
  y = c(3,4),
)

I want to find all groups for which all elements of x and x only are all NA, then remove those groups. "B" is filtered in because it has at least 1 non NA element.

I tried:

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 %>%
  filter(all(!is.na(x)))

but it seems that filters out if it finds at least 1 NA; I need the correct word, which is not all.

>Solution :

This will remove groups of column A if all elements of x are NA:

library(dplyr)

df %>%
  group_by(A) %>%
  filter(! all(is.na(x)))

# A tibble: 2 × 3
# Groups:   A [1]
#  A         x     y
#  <chr> <dbl> <dbl>
#1 B        NA     3
#2 B         1     4

Note that group "A" was removed because both cells in the column x are not defined.

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