Last active
January 16, 2020 16:21
-
-
Save romainfrancois/e9e0ed5d56413b95b095fbc0174d5f72 to your computer and use it in GitHub Desktop.
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(dplyr, warn.conflicts = FALSE) | |
library(purrr) | |
expressions <- function(vars, funs) { | |
#' make_expr("mpg", mean) | |
make_expr <- function(var, fun) { | |
expr((!!fun)(!!sym(var))) | |
} | |
names <- cross2(names(funs), vars) %>% | |
map_chr(paste, collapse = "__") | |
cross_df(list(var = vars, fun = funs)) %>% | |
pmap(make_expr) %>% | |
set_names(names) | |
} | |
variables <- setdiff(names(mtcars), "cyl") | |
mtcars %>% | |
group_by(cyl) %>% | |
summarise(!!!expressions(variables, list(mean = mean, sd = sd))) | |
#> # A tibble: 3 x 21 | |
#> cyl mean__mpg sd__mpg mean__disp sd__disp mean__hp sd__hp mean__drat | |
#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> | |
#> 1 4 26.7 105. 82.6 4.07 2.29 19.1 0.909 | |
#> 2 6 19.7 183. 122. 3.59 3.12 18.0 0.571 | |
#> 3 8 15.1 353. 209. 3.23 4.00 16.8 0 | |
#> # … with 13 more variables: sd__drat <dbl>, mean__wt <dbl>, sd__wt <dbl>, | |
#> # mean__qsec <dbl>, sd__qsec <dbl>, mean__vs <dbl>, sd__vs <dbl>, | |
#> # mean__am <dbl>, sd__am <dbl>, mean__gear <dbl>, sd__gear <dbl>, | |
#> # mean__carb <dbl>, sd__carb <dbl> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the help Romain. It seems to work even with a second grouping variable and adding min and max.
Unfortunately as with someone else's solution it doesn't work with my own data if my grouping variables are factors, but it does work if they're characters.