Reputation: 1546
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
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
Reputation: 78927
tbl %>%
group_by(category) %>%
filter(all(!is.na(values)))
category values
<chr> <dbl>
1 A 2
2 A 3
Upvotes: 2
Reputation: 18632
tbl %>%
filter(!category %in% category[is.na(values)])
Output
category values
<chr> <dbl>
1 A 2
2 A 3
Upvotes: 3
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