Grouping Over All Possible Combinations of Several Variables With dplyr

后端 未结 4 1817
遇见更好的自我
遇见更好的自我 2021-01-02 15:49

Given a situation such as the following

library(dplyr)
myData <- tbl_df(data.frame( var1 = rnorm(100), 
                             var2 = letters[1:3] %         


        
4条回答
  •  北荒
    北荒 (楼主)
    2021-01-02 16:09

    Inspired by the answers by Gregor and dimitris_ps, I wrote a dplyr style function that runs summarise for all combinations of group variables.

    summarise_combo <- function(data, ...) {
    
      groupVars <- group_vars(data) %>% map(as.name)
    
      groupCombos <-  map( 0:length(groupVars), ~combn(groupVars, ., simplify=FALSE) ) %>%
        unlist(recursive = FALSE)
    
      results <- groupCombos %>% 
        map(function(x) {data %>% group_by(!!! x) %>% summarise(...)} ) %>%
        bind_rows()
    
      results %>% select(!!! groupVars, everything())
    }
    

    Example

    library(tidyverse)
    mtcars %>% group_by(cyl, vs) %>% summarise_combo(cyl_n = n(), mean(mpg))
    

提交回复
热议问题