汇总给定列上的数据框并显示另一列 [英] Aggregate a dataframe on a given column and display another column
本文介绍了汇总给定列上的数据框并显示另一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在R中有以下格式的数据框:
I have a dataframe in R of the following form:
> head(data)
Group Score Info
1 1 1 a
2 1 2 b
3 1 3 c
4 2 4 d
5 2 3 e
6 2 1 f
我想使用max
函数将其汇总到Score
列之后
I would like to aggregate it following the Score
column using the max
function
> aggregate(data$Score, list(data$Group), max)
Group.1 x
1 1 3
2 2 4
但是我也想显示与每个组的Score
列最大值相关的Info
列.我不知道该怎么做.我想要的输出是:
But I also would like to display the Info
column associated to the maximum value of the Score
column for each group. I have no idea how to do this. My desired output would be:
Group.1 x y
1 1 3 c
2 2 4 d
有任何提示吗?
推荐答案
首先,您使用split
拆分数据:
First, you split the data using split
:
split(z,z$Group)
然后,为每个块选择具有最高得分的行:
Than, for each chunk, select the row with max Score:
lapply(split(z,z$Group),function(chunk) chunk[which.max(chunk$Score),])
最后缩小到data.frame do.call
ing rbind
:
Finally reduce back to a data.frame do.call
ing rbind
:
do.call(rbind,lapply(split(z,z$Group),function(chunk) chunk[which.max(chunk$Score),]))
结果:
Group Score Info
1 1 3 c
2 2 4 d
一行,没有魔法,速度很快,结果有好名字=)
One line, no magic spells, fast, result has good names =)
这篇关于汇总给定列上的数据框并显示另一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文