Reputation: 6578
I have a dataframe:
df <- data.frame(sample = c("R1", "R2", "R2", "R2", "R3", "R3"), event = c(1, 10, 10, 20, 3, 3), name = c('foo', 'bar', 'baz', 'baz', 'foo', 'baz'))
And I want to select rows grouped by sample
and event
where any of the rows in this group have a name == 'baz'
.
The desired output:
sample event name
2 R2 10 bar # another row in same sample, event group has name == 'baz'
3 R2 10 baz
4 R2 20 baz
5 R3 3 foo # another row with same sample, event group has name == 'baz'
6 R3 3 baz
Here's what I'm trying:
df %>%
group_by(sample, event) %>%
filter(name == 'baz')
Upvotes: 1
Views: 44
Reputation: 5923
You can simply use any()
!
df %>%
group_by(sample, event) %>%
filter(any(name == "baz"))
# A tibble: 5 x 3
# Groups: sample, event [3]
sample event name
<fct> <dbl> <fct>
1 R2 10 bar
2 R2 10 baz
3 R2 20 baz
4 R3 3 foo
5 R3 3 baz
Upvotes: 4