How to get the maximum value by group

前端 未结 5 1112
太阳男子
太阳男子 2020-11-27 07:00

I have a data.frame with two columns: year and score. The years go from 2000-2012 and each year can be listed multiple times. In the s

5条回答
  •  广开言路
    2020-11-27 07:52

    using base packages

    > df
      year score
    1 2000    18
    2 2001    22
    3 2000    21
    > aggregate(score ~ year, data=df, max)
      year score
    1 2000    21
    2 2001    22
    

    EDIT

    If you have additional columns that you need to keep, then you can user merge with aggregate to get those columns

    > df <- data.frame(year = c(2000, 2001, 2000), score = c(18, 22, 21) , hrs = c( 10, 11, 12))
    > df
      year score hrs
    1 2000    18  10
    2 2001    22  11
    3 2000    21  12
    > merge(aggregate(score ~ year, data=df, max), df, all.x=T)
      year score hrs
    1 2000    21  12
    2 2001    22  11
    

提交回复
热议问题