消除R中具有不同值的组 [英] Eliminate groups which have different values in R

查看:199
本文介绍了消除R中具有不同值的组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,如下所示

I have a data frame like below

sample <- data.frame(ID=1:9, Group=c('AA','AA','AA','BB','BB','CC','CC','BB','CC'), Value = c(1,1,1,2,2,2,3,2,3))

每个组应该具有相同的值。

Each group is supposed to have the same value.

ID       Group    Value
1        AA       1
2        AA       1
3        AA       1
4        BB       2
5        BB       2
6        CC       2
7        CC       3
8        BB       2
9        CC       3

如果您查看组CC,它的值不一样。

If you look at the group CC, it doesn't have the same value. It varys with 2 and 3.

我需要剔除没有唯一值的组。

I need to ellimiate groups that doesn't have unique value.

在上述情况下,组CC必须被删除。
结果应该如下

In the case above, group CC has to be removed. Result should be like below

ID       Group    Value
1        AA       1
2        AA       1
3        AA       1
4        BB       2
5        BB       2
8        BB       2

你能告诉我简单快速的代码在解决问题吗?

Would you tell me simple and fast code in R that solves the problem?

推荐答案

你可以样本的选择器使用 ave 许多不同的方式。

You can make a selector for sample using ave many different ways.

sample[ ave( sample$Value, sample$Group, FUN = function(x) length(unique(x)) ) == 1,]

sample[ ave( sample$Value, sample$Group, FUN = function(x) sum(x - x[1]) ) == 0,]

sample[ ave( sample$Value, sample$Group, FUN = function(x) diff(range(x)) ) == 0,]

这篇关于消除R中具有不同值的组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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