How to select the row with the maximum value in each group

后端 未结 16 2492
北荒
北荒 2020-11-21 04:18

In a dataset with multiple observations for each subject I want to take a subset with only the maximum data value for each record. For example, with a following dataset:

16条回答
  •  深忆病人
    2020-11-21 05:08

    I wasn't sure what you wanted to do about the Event column, but if you want to keep that as well, how about

    isIDmax <- with(dd, ave(Value, ID, FUN=function(x) seq_along(x)==which.max(x)))==1
    group[isIDmax, ]
    
    #   ID Value Event
    # 3  1     5     2
    # 7  2    17     2
    # 9  3     5     2
    

    Here we use ave to look at the "Value" column for each "ID". Then we determine which value is the maximal and then turn that into a logical vector we can use to subset the original data.frame.

提交回复
热议问题