首页 文章

使用dplyr的汇总和summarise_each一起?

提问于
浏览
10

我想同时将 dplyr::summarisedplyr::summarise_each 应用于分组数据帧 . 可能吗?

我的数据如下:

mydf <- data.frame(
    id = c(rep(1,2), rep(2, 3), rep(3, 4)), 
    amount = c(rep(1,4), rep(2,5)), 
    type1 = c(rep(1, 2), rep(0, 7)),
    type2 = c(rep(0, 4), rep(1, 5))
)
mydf
#  id amount type1 type2
#1  1      1     1     0
#2  1      1     1     0
#3  2      1     0     0
#4  2      1     0     0
#5  2      2     0     1
#6  3      2     0     1
#7  3      2     0     1
#8  3      2     0     1
#9  3      2     0     1

我想总结 id amount 变量并得到 type 变量的最大值 . 我知道我可以这样做:

mydf %>% 
    group_by(id) %>% 
    summarise(amount = sum(amount), type1 = max(type1), type2 = max(type2))

但是,我有很多 type 变量,所以我更喜欢这样的东西(但总和也是 amount ) .

mydf %>%
    group_by(id) %>%
    summarise_each(funs(max), matches("type"))

3 回答

  • 1

    使用 dplyr

    library(dplyr)
    
    mydf %>% 
         group_by(id) %>% 
         mutate(amount = sum(amount)) %>% 
         mutate_each(funs(max), matches("type")) %>%
         unique
    
    #Source: local data table [3 x 4]
    
    #  id amount type1 type2
    #1  1      2     1     0
    #2  2      4     0     1
    #3  3      8     0     1
    

    或者只是像@HongOoi所指出的那样

    mydf %>% 
         group_by(id) %>% 
         mutate(amount=sum(amount)) %>% 
         summarise_each(funs(max))
    
  • 8

    我不确定使用 dplyr 的惯用方法,但这是非常惯用的 data.table

    library(data.table)
    setDT(mydf)[, c(amount = sum(amount), 
                    lapply(.SD[, grep("type", names(mydf), value = TRUE), with = FALSE], max)),
                by = id]
    #    id amount type1 type2
    # 1:  1      2     1     0
    # 2:  2      4     0     1
    # 3:  3      8     0     1
    

    基本上,我们使用 c 组合两个操作,而 lapply(.SD, max) 代表 dplyr 中的 mutate_eachmatches 只是 grep 的包装(如清楚显示in the source code) . with = FALSE 用于 data.table.SD 父框架(代表 S ub D ata)中列名的标准评估 .

  • 7

    使用 dplyr 的更一般方法可能是:

    mydf %>%
      group_by(id) %>%
      mutate_each('sum', amount) %>%
      mutate_each('max', matches("type")) %>%
      summarise_each('first', amount, matches("type"))
    

    这样做的好处是只能将一个聚合函数应用于Veerendra Gadekar原始答案所拥有的每一列 . 如果我们需要 sd 或类似代替 max ,它会派上用场,Hong Ooi的解决方案会在这种情况下破裂 . 如果有字符列,它也会中断 . 第三个优点是它丢弃了不属于计算的列 .

    另见my related question .

相关问题