Reputation: 601
I'm trying to subset a dataframe that looks like
df<-data.frame(id=c(1,1,1,2,2,2,3,3,3),
aa=c(NA,NA,1,1,NA,1,NA,NA,2))
I want to retain data on all ids with at least one entry in aa equal to 1. The expected output looks like
id aa
1 1 NA
2 1 NA
3 1 1
4 2 1
5 2 NA
6 2 1
I tried
df %>%
group_by(id) %>%
filter(aa == 1 )
but it's not working as expected. Any help is greatly appreciated.
Upvotes: 0
Views: 28
Reputation: 21749
You can use any
df <- df %>%
group_by(id) %>%
filter(any(aa == 1))
print(df)
id aa
<dbl> <dbl>
1 1 NA
2 1 NA
3 1 1
4 2 1
5 2 NA
6 2 1
Upvotes: 1