return rows with max/min value of column, by group, using plyr::ddply

风格不统一 提交于 2019-12-12 01:46:00

问题


I found an answer (now deleted) to this question, and I'm curious why it doesn't work.

Question is: return the row corresponding to the minimum value, by group.

So for example, given the dataset:

df <- data.frame(State = c(rep('AK',4),rep('RI',4)),
                   Company = LETTERS[1:8],
                   Employees = c(82L, 104L, 37L, 24L, 19L, 118L, 88L, 42L)) 

...the correct answer is:

    State Company Employees
 1:    AK       D        24
 2:    RI       E        19

as can be obtained, for example, by

library(data.table); setDT(df)[ , .SD[which.min(Employees)], by = State]

My question is why this plyr::ddply command doesn't work:

library(plyr)
ddply(df, .(State), summarise, Employees=min(Employees), 
      Company=Company[which.min(Employees)])
# returns:
#   State Employees Company
# 1    AK        24       A
# 2    RI        19       E

In other words, why is which.min(Employees) returning 1 for each group, instead of c(4,1)? Note that outside of ddply, this works:

summarise(df, minEmp = min(Employees), whichMin = which.min(Employees))
#   minEmp whichMin
# 1     19        5

I don't use plyr much, but I'd like to know the right way to do it, if there's a reasonable one.


回答1:


i'm getting the correct answer. not sure about your case..

library(plyr)
ddply(df, .(State), function(x) x[which.min(x$Employees),])
  State Company Employees
1    AK       D        24
2    RI       E        19


来源:https://stackoverflow.com/questions/42098881/return-rows-with-max-min-value-of-column-by-group-using-plyrddply

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!