我有一个数据框:
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'))
我想选择按sample
和event
分组的行,其中该组中的任何行都具有name == 'baz'
。
所需的输出:
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
这就是我要尝试的:
df %>%
group_by(sample, event) %>%
filter(name == 'baz')
答案 0 :(得分:4)
您只需使用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