根据分组条件过滤数据集

时间:2020-08-28 18:31:04

标签: r dplyr

这可能是一个愚蠢的问题,但我无法弄清楚如何过滤df来保持id与在factor_A的所有级别中都存在的条件匹配的行:

df = data.frame(id    = c(1,1,1,2,2,3,3), 
                factor_A = c(1,2,3,1,2,1,3))

所需的df1仅保留包含id = 1的行,因为它存在于factor_A = 1,2和3中:

     id factor_A
1     1     1
2     1     2
3     1     3

3 个答案:

答案 0 :(得分:1)

这应该做

library(dplyr)

df = data.frame(id    = c(1,1,1,2,2,3,3), 
                factor_A = c(1,2,3,1,2,1,3))

df %>% group_by(id) %>% 
  filter(length(unique(factor_A)) == length(unique(df$factor_A)))

答案 1 :(得分:1)

我建议使用dplyr方法。您可以计算每个ID的级别数,然后进行过滤。由于您的因子变量具有3个级别,因此您将使这些行的Flag等于3:

library(dplyr)
#Data
df = data.frame(id    = c(1,1,1,2,2,3,3), 
                factor_A = c(1,2,3,1,2,1,3))
#Create flag
df %>% group_by(id) %>%
  #Count levels
  mutate(Flag=n_distinct(factor_A)) %>%
  #Filter only rows with 3
  filter(Flag==3) %>% select(-Flag)

输出:

# A tibble: 3 x 2
# Groups:   id [1]
     id factor_A
  <dbl>    <dbl>
1     1        1
2     1        2
3     1        3

答案 2 :(得分:1)

我们可以使用base R

subset(df, id %in% names(which(!rowSums(!table(df) > 0))))
#  id factor_A
#1  1        1
#2  1        2
#3  1        3
相关问题