Skip to content

Instantly share code, notes, and snippets.

@TimTeaFan
Last active June 14, 2021 22:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TimTeaFan/0f359f030dc1f25af91e384801ea33ce to your computer and use it in GitHub Desktop.
Save TimTeaFan/0f359f030dc1f25af91e384801ea33ce to your computer and use it in GitHub Desktop.
Totals and subtotals with dplyr and bind_rows
library(dplyr)
set.seed(123)
dat <- tibble(main_grp = rep(c("a", "b"), each = 4),
sub_grp = rep(c("x", "y"), 4),
value = rnorm(8))
dat %>%
bind_rows(., mutate(dat, sub_grp = "subtotal")) %>%
bind_rows(., mutate(dat, main_grp = "total", sub_grp = "")) %>%
group_by(main_grp, sub_grp) %>%
summarise(sum = sum(value)) %>%
arrange(main_grp,
main_grp == "total",
sub_grp == "subtotal")
#> `summarise()` has grouped output by 'main_grp'. You can override using the `.groups` argument.
#> # A tibble: 7 x 3
#> # Groups: main_grp [3]
#> main_grp sub_grp sum
#> <chr> <chr> <dbl>
#> 1 a "x" 0.998
#> 2 a "y" -0.160
#> 3 a "subtotal" 0.839
#> 4 b "x" 0.590
#> 5 b "y" 0.450
#> 6 b "subtotal" 1.04
#> 7 total "" 1.88
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment