SiH
SiH

Reputation: 1546

remove group if any member containes NA in R

How can I remove entire group if one of its values is NA. For ex - remove category B because it contains NA.

library(dplyr)

tbl = tibble(category = c("A", "A", "B", "B"),
             values = c(2, 3, 1, NA))

Upvotes: 2

Views: 1319

Answers (4)

Ronak Shah
Ronak Shah

Reputation: 388982

You can get the categories which has at least one NA value and exclude them.

subset(tbl, !category %in% unique(category[is.na(values)]))

#  category values
#  <chr>     <dbl>
#1 A             2
#2 A             3

If you prefer dplyr::filter.

library(dplyr)

tbl %>% filter(!category %in% unique(category[is.na(values)]))

Upvotes: 1

TarJae
TarJae

Reputation: 78927

tbl %>% 
  group_by(category) %>% 
  filter(all(!is.na(values)))
  category values
  <chr>     <dbl>
1 A             2
2 A             3

Upvotes: 2

LMc
LMc

Reputation: 18632

tbl %>% 
  filter(!category %in% category[is.na(values)])

Output

  category values
  <chr>     <dbl>
1 A             2
2 A             3

Upvotes: 3

akrun
akrun

Reputation: 887118

We can use filter after grouping by 'category'

library(dplyr)
tbl %>% 
    group_by(category) %>% 
    filter(!any(is.na(values))) %>%
    ungroup

-output

# A tibble: 2 x 2
  category values
  <chr>     <dbl>
1 A             2
2 A             3

Upvotes: 5

Related Questions