Extract row corresponding to minimum value of a variable by group

前端 未结 6 1824
孤独总比滥情好
孤独总比滥情好 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 04:45

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

    data[data$Employees == ave(data$Employees, data$State, FUN=min),]
    #  State Company Employees
    #4    AK       D        24
    #5    RI       E        19
    

    Or compare it already in the function.

    data[as.logical(ave(data$Employees, data$State, FUN=function(x) x==min(x))),]
    #data[ave(data$Employees, data$State, FUN=function(x) x==min(x))==1,] #Variant
    #  State Company Employees
    #4    AK       D        24
    #5    RI       E        19
    

提交回复
热议问题