选择具有多个独特价值的群体 [英] Select groups with more than one distinct value
问题描述
我有带有分组变量( from)和值( number)的数据:
I have data with a grouping variable ("from") and values ("number"):
from number
1 1
1 1
2 1
2 2
3 2
3 2
我想对数据进行子集处理,并选择具有两个或多个唯一值的组。在我的数据中,只有第2组具有多个不同的数字,所以这是期望的结果:
I want to subset the data and select groups which have two or more unique values. In my data, only group 2 has more than one distinct 'number', so this is the desired result:
from number
2 1
2 2
推荐答案
几种可能性,这是我的最爱
Several possibilities, here's my favorite
library(data.table)
setDT(df)[, if(+var(number)) .SD, by = from]
# from number
# 1: 2 1
# 2: 2 2
基本上,每个组我们检查是否有方差,如果 TRUE
,则返回组值
Basically, per each group we are checking if there is any variance, if TRUE
, then return the group values
使用基数R,我会选择
df[as.logical(with(df, ave(number, from, FUN = var))), ]
# from number
# 3 2 1
# 4 2 2
编辑:对于非数值数据,您可以尝试使用 data.table
的开发版本(或使用 length(unique(number) )> 1
Edit: for a non numerical data you could try the new uniqueN
function for the devel version of data.table
(or use length(unique(number)) > 1
instead
setDT(df)[, if(uniqueN(number) > 1) .SD, by = from]
这篇关于选择具有多个独特价值的群体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!