聚集给定列上的数据框并显示另一列

我在R中有以下格式的数据框:


> 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

我想Score使用max功能将其汇总到列之后


> aggregate(data$Score, list(data$Group), max)


  Group.1         x

1       1         3

2       2         4

但我也想显示与每个组Info的Score列最大值相关联的列。我不知道该怎么做。我想要的输出将是:


  Group.1         x        y

1       1         3        c

2       2         4        d

有什么提示吗?


牧羊人nacy
浏览 552回答 3
3回答

慕森卡

基本的R解决方案是将的输出aggregate()与一个merge()步骤结合起来。我发现公式接口aggregate()比标准接口更有用,部分原因是输出中的名称更好,所以我将使用它:该aggregate()步骤是maxs <- aggregate(Score ~ Group, data = dat, FUN = max)这merge()一步很简单merge(maxs, dat)这给了我们想要的输出:R> maxs <- aggregate(Score ~ Group, data = dat, FUN = max)R> merge(maxs, dat)&nbsp; Group Score Info1&nbsp; &nbsp; &nbsp;1&nbsp; &nbsp; &nbsp;3&nbsp; &nbsp; c2&nbsp; &nbsp; &nbsp;2&nbsp; &nbsp; &nbsp;4&nbsp; &nbsp; d当然,您可以将其粘贴为单线(中介步骤更多用于说明):merge(aggregate(Score ~ Group, data = dat, FUN = max), dat)我使用公式接口的主要原因是它返回的数据帧具有正确names的合并步骤。这些是原始数据集中的列的名称dat。我们需要具有aggregate()正确名称的输出,以便merge()知道原始数据帧和聚合数据帧中的哪些列匹配。标准接口给出奇数名称,无论您以哪种方式调用它:R> aggregate(dat$Score, list(dat$Group), max)&nbsp; Group.1 x1&nbsp; &nbsp; &nbsp; &nbsp;1 32&nbsp; &nbsp; &nbsp; &nbsp;2 4R> with(dat, aggregate(Score, list(Group), max))&nbsp; Group.1 x1&nbsp; &nbsp; &nbsp; &nbsp;1 32&nbsp; &nbsp; &nbsp; &nbsp;2 4我们可以merge()在这些输出上使用,但是我们需要做更多的工作告诉R哪些列匹配。

DIEA

这是使用该plyr包装的解决方案。下面的代码行实际上告诉ddply我们首先按组对数据进行分组,然后在每个组内返回一个子集,其中“分数”等于该组中的最大分数。library(plyr)ddply(data, .(Group), function(x)x[x$Score==max(x$Score), ])&nbsp; Group Score Info1&nbsp; &nbsp; &nbsp;1&nbsp; &nbsp; &nbsp;3&nbsp; &nbsp; c2&nbsp; &nbsp; &nbsp;2&nbsp; &nbsp; &nbsp;4&nbsp; &nbsp; d而且,正如@SachaEpskamp指出的那样,可以将其进一步简化为:ddply(df, .(Group), function(x)x[which.max(x$Score), ])(which.max如果有的话,它还具有返回多条最大行的优点)。
打开App,查看更多内容
随时随地看视频慕课网APP