此问题已经在这里有了答案:
我正在尝试对同一列中的ID与两个值相关联的行进行子集化或过滤(每个“ ID”和相关条件“ DIR”都有一行)
我无法在dplyr过滤器或子集函数中找到答案
x <- data.frame("ID"=c(1,2,2,3,3,3,4,4,4,4),
"DIR"=c("up","up","down","up","up","up","down","down","down","down"))
我都尝试过两种变化:
subset(x, DIR=="up" & DIR=="down")
x %>% group_by(ID) %>% filter(DIR=="up" & DIR=="down")
我想要的是ID#2的两行,因为它是DIR列中唯一同时具有“ up”和“ down”的ID
没有返回结果
按“ ID”分组后,通过检查filter
all
(vector
)的元素是c("up", "down")
列“ DIR”来%in%
library(dplyr)
x %>%
group_by(ID) %>%
filter(all(c("up", "down") %in% DIR) )
# A tibble: 2 x 2
# Groups: ID [1]
# ID DIR
# <dbl> <fct>
#1 2 up
#2 2 down
或使用base R
i1 <- with(x, as.logical(ave(as.character(DIR), ID, FUN =
function(x) all(c("up", "down") %in% x))))
x[i1, ]
# ID DIR
#2 2 up
#3 2 down