Created
April 7, 2020 21:52
-
-
Save tmastny/61c889a6b659e91d3335335c204f9749 to your computer and use it in GitHub Desktop.
Use dplyr 1.0.0 rowwise to add summary rows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(ggplot2) | |
library(tidyr) | |
library(dplyr, warn.conflicts = FALSE) | |
diamonds_sum <- diamonds %>% | |
mutate(across(cut, as.character)) %>% | |
group_by(cut) %>% | |
summarise(across(price, sum), across(carat, n_distinct), n = n()) | |
diamonds_sum | |
#> # A tibble: 5 x 4 | |
#> cut price carat n | |
#> * <chr> <int> <int> <int> | |
#> 1 Fair 7017600 185 1610 | |
#> 2 Good 19275009 199 4906 | |
#> 3 Ideal 74513487 232 21551 | |
#> 4 Premium 63221498 251 13791 | |
#> 5 Very Good 48107623 231 12082 | |
transpose_df <- function(x, col, name) { | |
x %>% | |
pivot_longer(-{{ col }}, names_to = name) %>% | |
pivot_wider(names_from = {{ col }}) | |
} | |
diamonds_sum %>% | |
transpose_df(cut, "feature") %>% | |
rowwise(feature) %>% | |
mutate(total = sum(c_across())) %>% | |
transpose_df(feature, "cut") | |
#> # A tibble: 6 x 4 | |
#> cut price carat n | |
#> <chr> <int> <int> <int> | |
#> 1 Fair 7017600 185 1610 | |
#> 2 Good 19275009 199 4906 | |
#> 3 Ideal 74513487 232 21551 | |
#> 4 Premium 63221498 251 13791 | |
#> 5 Very Good 48107623 231 12082 | |
#> 6 total 212135217 1098 53940 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment