选择具有多个不同值的组 [英] Select groups with more than one distinct value
问题描述
我有包含分组变量(来自")和值(数字")的数据:
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,我会选择
With base R, I would go with
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屋!