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

后端 未结 16 2640
北荒
北荒 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:03

    In base you can use ave to get max per group and compare this with pt and get a logical vector to subset the data.frame.

    group[group$pt == ave(group$pt, group$Subject, FUN=max),]
    #  Subject pt Event
    #3       1  5     2
    #7       2 17     2
    #9       3  5     2
    

    Or compare it already in the function.

    group[as.logical(ave(group$pt, group$Subject, FUN=function(x) x==max(x))),]
    #group[ave(group$pt, group$Subject, FUN=function(x) x==max(x))==1,] #Variant
    #  Subject pt Event
    #3       1  5     2
    #7       2 17     2
    #9       3  5     2
    

提交回复
热议问题