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

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

    A dplyr solution:

    library(dplyr)
    ID <- c(1,1,1,2,2,2,2,3,3)
    Value <- c(2,3,5,2,5,8,17,3,5)
    Event <- c(1,1,2,1,2,1,2,2,2)
    group <- data.frame(Subject=ID, pt=Value, Event=Event)
    
    group %>%
        group_by(Subject) %>%
        summarize(max.pt = max(pt))
    

    This yields the following data frame:

      Subject max.pt
    1       1      5
    2       2     17
    3       3      5
    

提交回复
热议问题