当by参数基于多列时,r聚合最大值



我有一个数据集,如下

 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)

这没有起作用,尝试了dcastwhich.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)] 

最新更新