如何使用一列中的选择值过滤行但使用常见ID?

时间:2018-02-11 19:34:12

标签: r dplyr

我的数据框df包含以下列:

ID <- c(1,1,1,2,2,2,2,3,3)
value <- c("A","B","C","C","C","C","C","B","C")

我想过滤具有值ABC的行作为公共ID。

过滤器的预期结果:

ID    Value
1     A
1     B
1     C
3     B
3     C

我该怎么做?

这不起作用

df %>% group_by(ID) %>% filter((Value == "A" | Value == "B") & Value == "C")

1 个答案:

答案 0 :(得分:2)

如果组中的任何元素为any(),您可以使用TRUE返回TRUE。如此工作的例子:

ID <- c(1,1,1,2,2,2,2,3,3)
value <- c("A","B","C","C","C","C","C","B","C")
df <- data.frame(ID,value)

library(dplyr)
df %>% 
  group_by(ID) %>% 
  filter(any(value %in% c("A","B")) & any(value == "C"))

输出:

# A tibble: 5 x 2
# Groups:   ID [2]
     ID  value
  <dbl> <fctr>
1     1      A
2     1      B
3     1      C
4     3      B
5     3      C

希望这有帮助!