r aggregate max when by parameter基于多列
r aggregate max when by parameter is based on multiple columns
我有一个数据集如下
Id Date Subject Score
12221 08/01/2007 Math 89
12221 08/01/2007 Math 92
12221 08/01/2007 Math 78
12221 11/01/2007 Math 36
12221 11/01/2007 Math 45
12221 11/01/2007 Math 24
2856 03/18/2004 Science 56
2856 03/18/2004 Science 49
2856 03/18/2004 Science 84
我试图只保留 ID、日期和主题组合的分数最大的行,例如最终输出应如下所示
Id Date Subject Score
12221 08/01/2007 Math 92
12221 11/01/2007 Math 45
2856 03/18/2004 Science 84
我尝试了 aggregate
功能,
aggregate(score ~ list(Id,Date,Subject), df, max)
这没有用,尝试了 dcast
、which.max
等,但都没有产生预期的结果,非常感谢任何解决此问题的帮助。
我们可以使用聚合
aggregate(Score~., df1, FUN= max)
# Id Date Subject Score
#1 12221 08/01/2007 Math 92
#2 12221 11/01/2007 Math 45
#3 2856 03/18/2004 Science 84
或 dplyr
library(dplyr)
df1 %>%
group_by(Id, Date, Subject) %>%
summarise(Score= max(Score))
或使用data.table
library(data.table)
setDT(df1)[, list(Score= max(Score)), by = .(Id, Date, Subject)]
我有一个数据集如下
Id Date Subject Score
12221 08/01/2007 Math 89
12221 08/01/2007 Math 92
12221 08/01/2007 Math 78
12221 11/01/2007 Math 36
12221 11/01/2007 Math 45
12221 11/01/2007 Math 24
2856 03/18/2004 Science 56
2856 03/18/2004 Science 49
2856 03/18/2004 Science 84
我试图只保留 ID、日期和主题组合的分数最大的行,例如最终输出应如下所示
Id Date Subject Score
12221 08/01/2007 Math 92
12221 11/01/2007 Math 45
2856 03/18/2004 Science 84
我尝试了 aggregate
功能,
aggregate(score ~ list(Id,Date,Subject), df, max)
这没有用,尝试了 dcast
、which.max
等,但都没有产生预期的结果,非常感谢任何解决此问题的帮助。
我们可以使用聚合
aggregate(Score~., df1, FUN= max)
# Id Date Subject Score
#1 12221 08/01/2007 Math 92
#2 12221 11/01/2007 Math 45
#3 2856 03/18/2004 Science 84
或 dplyr
library(dplyr)
df1 %>%
group_by(Id, Date, Subject) %>%
summarise(Score= max(Score))
或使用data.table
library(data.table)
setDT(df1)[, list(Score= max(Score)), by = .(Id, Date, Subject)]