选择具有多个独特价值的群体 [英] Select groups with more than one distinct value

查看:74
本文介绍了选择具有多个独特价值的群体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有带有分组变量( 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






编辑:对于非数值数据,您可以尝试使用uniqueN 函数/ wiki / Installation rel = nofollow> 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆