Select 个组,每个组有一个以上的不同值

Select groups with more than one distinct value per group

我有如下数据:

ID  category class
1   a        m  
1   a        s
1   b        s
2   a        m
3   b        s
4   c        s
5   d        s

我想通过仅包括具有多个 (> 1) 个不同类别的那些 "ID" 来对数据进行子集化。

我的预期输出:

ID  category class
1   a        m
1   a        s
1   b        s

有办法吗?

我试过了

library(dplyr)
df %>% 
  group_by(ID) %>%
  filter(n_distinct(category, class) > 1)

但是它给了我一个错误:

# Error: expecting a single value

使用data.table

library(data.table) #see: https://github.com/Rdatatable/data.table/wiki for more
setDT(data) #convert to native 'data.table' type by reference
data[ , if(uniqueN(category) > 1) .SD, by = ID]

uniqueNdata.tablelength(unique()) 的(快速)原生掩码,而 .SD 只是整个 data.table(在更一般的情况下,它可以表示列的子集,例如,当 .SDcols 参数被激活时)。所以基本上中间语句(j,列选择参数)说到 return 与 ID 关联的所有列和行,其中至少有两个不同的 [=20= 值].

使用 by 参数扩展到涉及多列计数的情况。