如何以每行的模式(最常见)值聚合R中的数据? [英] How to aggregate data in R with mode (most common) value for each row?
本文介绍了如何以每行的模式(最常见)值聚合R中的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我有一个数据集,
I have a data set for example,
Data <- data.frame(
groupname = as.factor(sample(c("a", "b", "c"), 10, replace = TRUE)),
someuser = sample(c("x", "y", "z"), 10, replace = TRUE))
groupname someuser
1 a x
2 b y
3 a x
4 a y
5 c z
6 b x
7 b x
8 c x
9 c y
10 c x
如何汇总数据以便获取:
How do I aggregate the data so that I get:
groupname someuser
a x
b x
c x
这是每个组名最常见的值
that is the most common value for each of the groupname.
PS:根据我的设置,我只能使用2个pakcages-plyr& lubridate
PS: Given my setup, I have the limitation of using only 2 pakcages - plyr & lubridate
推荐答案
您可以结合使用函数来查找具有聚集的模式。
You can combine this function for finding the mode with aggregate.
Mode <- function(x) {
ux <- unique(x)
ux[which.max(tabulate(match(x, ux)))]
}
aggregate(someuser ~ groupname, Data, Mode)
groupname someuser
1 a x
2 b x
3 c x
请注意,如果出现平局,它将仅返回第一个值。
Note that in the event of a tie, it will only return the first value.
这篇关于如何以每行的模式(最常见)值聚合R中的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文