Extract row corresponding to minimum value of a variable by group

前端 未结 6 1820
孤独总比滥情好
孤独总比滥情好 2020-11-22 04:04

I wish to (1) group data by one variable (State), (2) within each group find the row of minimum value of another variable (Employees), and (3) extr

6条回答
  •  感情败类
    2020-11-22 05:01

    Slightly more elegant:

    library(data.table)
    DT[ , .SD[which.min(Employees)], by = State]
    
       State Company Employees
    1:    AK       D        24
    2:    RI       E        19
    

    Slighly less elegant than using .SD, but a bit faster (for data with many groups):

    DT[DT[ , .I[which.min(Employees)], by = State]$V1]
    

    Also, just replace the expression which.min(Employees) with Employees == min(Employees), if your data set has multiple identical min values and you'd like to subset all of them.

    See also Subset rows corresponding to max value by group using data.table.

提交回复
热议问题