我的数据框df
包含以下列:
ID <- c(1,1,1,2,2,2,2,3,3)
value <- c("A","B","C","C","C","C","C","B","C")
我想过滤具有值A
或B
和C
的行作为公共ID。
过滤器的预期结果:
ID Value
1 A
1 B
1 C
3 B
3 C
我该怎么做?
这不起作用
df %>% group_by(ID) %>% filter((Value == "A" | Value == "B") & Value == "C")
答案 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
希望这有帮助!