Extract row corresponding to minimum value of a variable by group

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

    The base function by is often useful for working with block data in data.frames. For example

    by(data, data$State, function(x) x[which.min(x$Employees), ] )
    

    It does return the data in a list, but you can collapse that with

    do.call(rbind, by(data, data$State, function(x) x[which.min(x$Employees), ] ))
    

提交回复
热议问题