Programmatically dropping a `group_by` field in dplyr

前端 未结 3 1156
挽巷
挽巷 2021-02-20 05:49

I\'m writing functions that take in a data.frame and then do some operations. I need to add and subtract items from the group_by criteria in order to g

3条回答
  •  半阙折子戏
    2021-02-20 06:35

    Maybe something like this to remove grouping variables from the end of the list back:

    grouped %>% 
     group_by(b, add=TRUE) -> grouped
    grouped %>% group_by_at(.vars = group_vars(.)[-2])
    

    or use head or tail or something on the output from group_vars for more control.

    It would be interesting to have this sort of utility function available more generally:

    peel_groups <- function(.data,n){
      .data %>%
        group_by_at(.vars = head(group_vars(.data),-n))
    }
    

    A more thought out version would likely include more careful checks on n being out of bounds.

提交回复
热议问题