【问题标题】:dplyr::group_by() with multiple variables but NOT intersectiondplyr::group_by() 具有多个变量但不是交集
【发布时间】:2016-11-28 18:49:55
【问题描述】:

当您group_by 多个变量时,dplyr 有助于找到这些组的交集。

例如,

mtcars %>% 
  group_by(cyl, am) %>%
  summarise(mean(disp))

产量

Source: local data frame [6 x 3]
Groups: cyl [?]

    cyl    am `mean(disp)`
  <dbl> <dbl>        <dbl>
1     4     0     135.8667
2     4     1      93.6125
3     6     0     204.5500
4     6     1     155.0000
5     8     0     357.6167
6     8     1     326.0000

我的问题是,有没有办法提供多个变量,但总结一下?如果你手动执行此操作,我想要得到的输出,一个变量一个变量。

df_1 <- 
  mtcars %>% 
  group_by(cyl) %>%
  summarise(est = mean(disp)) %>%
  transmute(group = paste0("cyl_", cyl), est)

df_2 <- 
  mtcars %>% 
  group_by(am) %>%
  summarise(est = mean(disp)) %>%
  transmute(group = paste0("am_", am), est)

bind_rows(df_1, df_2)

以上代码产生

# A tibble: 5 × 2
  group      est
  <chr>    <dbl>
1 cyl_4 105.1364
2 cyl_6 183.3143
3 cyl_8 353.1000
4  am_0 290.3789
5  am_1 143.5308

理想情况下,语法类似于

mtcars %>%
group_by(cyl, am, intersection = FALSE) %>%
summarise(est = mean(disp))

tidyverse 中是否存在类似的内容?

(ps,我知道上表中的 group 变量并不整洁,因为它包含两个变量合而为一,但我保证出于我的目的,它是整洁的,好吗?:))

【问题讨论】:

    标签: r dplyr tidyverse


    【解决方案1】:

    我猜你要找的是tidyr 包...

    gather 首先复制数据集,以便每个因子有 n 行,根据这些因子进行分组; mutate 然后创建分组变量。

    library(dplyr)
    library(tidyr)
    
    mtcars %>%
      gather(col, value, cyl, am) %>% 
      mutate(group = paste(col, value, sep = "_")) %>%
      group_by(group) %>% 
      summarise(est = mean(disp))
    

    【讨论】:

    • 这是一个很好的解决方案。小的编辑使更通用的 df %>% gather(col, value, X1, X2, X3, X4) %>% mutate(group = paste0(col, "_", value))
    【解决方案2】:

    purrr 替代方案:

    library(tidyverse)
    
    map(c('cyl', 'am'), 
        ~ mtcars %>% 
          group_by_(.x) %>%
          summarise(est = mean(disp)) %>%
          transmute_(group = lazyeval::interp(~paste0(.x, '_', y), y = as.name(.x)),
                     ~est)) %>% 
      bind_rows()
    
    # A tibble: 5 × 2
      group      est
      <chr>    <dbl>
    1 cyl_4 105.1364
    2 cyl_6 183.3143
    3 cyl_8 353.1000
    4  am_0 290.3789
    5  am_1 143.5308
    

    【讨论】:

      【解决方案3】:

      plyr 包更简单。

      library(plyr)
      mtcars %>% 
        ddply(c("cyl", "am"), .fun = function(x) {
          mean(x$disp)
        })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-20
        • 2014-03-06
        • 2016-12-03
        • 2016-09-17
        • 2019-08-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多