首页 > 解决方案 > 如何为另一列中的每个唯一值返回列的最大值?

问题描述

aggregate(df$count, list(df$sport, df$color), sum)

聚合返回以下数据框,但我只想返回每种颜色的最大计数:

Sport      Color     Count
Baseball   Blue      5
Football   Blue      10
Basketball Blue      7
Baseball   Red       6
Football   Red       9
Basketball Red       13

我希望代码返回:

Sport      Color     Count
Football   Blue      10
Basketball Red       13

因为足球在蓝色组中的人数最多,而篮球在红色组中的人数最多。

标签: raggregatetapply

解决方案


另一种基本选择:

do.call(rbind, by(df, df$Color, function(z) z[which.max(z$Count),]))
#           Sport Color Count
# Blue   Football  Blue    10
# Red  Basketball   Red    13

或者一个整洁的版本:

library(dplyr)
df %>%
  group_by(Color) %>%
  slice(which.max(Count)) %>%
  ungroup()
# # A tibble: 2 x 3
#   Sport      Color Count
#   <chr>      <chr> <int>
# 1 Football   Blue     10
# 2 Basketball Red      13

推荐阅读