r - 如何为另一列中的每个唯一值返回列的最大值?
问题描述
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
因为足球在蓝色组中的人数最多,而篮球在红色组中的人数最多。
解决方案
另一种基本选择:
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
推荐阅读
- jmeter - 无法通过运行 Jmeter 脚本来实现预期的吞吐量,因为预期的吞吐量更多但变得非常少
- javafx - 设置“快速”单击 - JavaFx
- php - 使用会话可以直接登录,无需在PHP中匹配电子邮件和密码
- stm32f4 - STM32F4 - 如何检测取出的电池
- c# - 如何将 function.json 添加到现有的 .NET 函数 2.0
- coffeescript - 使用 Slack API 上传时出现 no_file_data 错误
- typescript - 定义一个类型,它是一个以另一个类型定义的键开头的字符串?
- mongodb - yii2 mongodb - 如何在集合子数组中查找元素
- calendar - 修改日历中的事件以成为重复事件
- php - 在php中将单词排列在数组中