Skip to content

Instantly share code, notes, and snippets.

@thisisnic
Last active December 7, 2018 18:43
Show Gist options
  • Save thisisnic/e77d288ffa79090602e87dcec670f240 to your computer and use it in GitHub Desktop.
Save thisisnic/e77d288ffa79090602e87dcec670f240 to your computer and use it in GitHub Desktop.
A handy scoped dplyr function is group_by_if() which allows you to apply a predicate function to columns to determine if they are part of the grouping. Here, I group by all factors in my data & then count how many members there are in each group.

Code:

library(dplyr)
group_by_if(ggplot2::diamonds, is.factor) %>%
  count()

Output:

# A tibble: 276 x 4
# Groups:   cut, color, clarity [276]
   cut   color clarity     n
   <ord> <ord> <ord>   <int>
 1 Fair  D     I1          4
 2 Fair  D     SI2        56
 3 Fair  D     SI1        58
 4 Fair  D     VS2        25
 5 Fair  D     VS1         5
 6 Fair  D     VVS2        9
 7 Fair  D     VVS1        3
 8 Fair  D     IF          3
 9 Fair  E     I1          9
10 Fair  E     SI2        78
# ... with 266 more rows
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment