在使用ddply进行汇总时如何添加列

时间:2015-02-12 19:29:36

标签: r dataframe plyr

我的问题是使用ddply函数汇总data.frame,例如下面。

该功能用于创建具有最大评级的新数据框和相应的公司。缺少的是第一个数据框中的相应ID。

我试图调用ID变量,但这会导致错误消息。 我对与最高评级相对应的ID感兴趣。

非常感谢您的帮助!

dat <- data.frame(ID = c("A11", "A12", "A21","A22","A23","A31"), 
              company =  c("CompA","CompA","CompB","CompB","CompB","CompC"),
              rating = c(1,4,2,5,3,4)
              )

company  ID ratingMax
1   CompA A11         1
2   CompA A12         4
3   CompB A21         2
4   CompB A22         5
5   CompB A23         3             
6   CompC A31         4

library(plyr)
ddply(dat, "company", summarise, ratingMax = max(rating))

company ratingMax
1   CompA         4
2   CompB         5
3   CompC         4

ddply(dat, "company", summarise, ratingMax = max(rating), ID = ID)
Error: length(rows) == 1 is not TRUE

2 个答案:

答案 0 :(得分:4)

你可以尝试

 library(plyr) 
 ddply(dat, "company", summarise, ratingMax = max(rating),
             ID = ID[which.max(rating)])
 #  company ratingMax  ID
 #1   CompA         4 A12
 #2   CompB         5 A22
 #3   CompC         4 A31

或使用dplyr

 library(dplyr)
 dat %>% 
      group_by(company) %>% 
      summarise(ratingMax=max(rating), ID=ID[which.max(rating)])
 #  company ratingMax  ID
 #1   CompA         4 A12
 #2   CompB         5 A22
 #3   CompC         4 A31

或者您可以使用filter

   dat %>% 
       group_by(company) %>% 
       filter(row_number() %in% which.max(rating))

或者按照@docendo discimus的提议使用slice(会更快更紧凑)

  dat %>% 
      group_by(company) %>%
      slice(which.max(rating))

答案 1 :(得分:3)

这是一个快速的data.table解决方案,它可以帮助您手动命名列(如果您想要显示更多列的话)

library(data.table)
setDT(dat)[, .SD[which.max(rating)], by = company]
#    company  ID rating
# 1:   CompA A12      4
# 2:   CompB A22      5
# 3:   CompC A31      4