-
-
Save maurolepore/7e48f5c9531858a028766145808f98ae to your computer and use it in GitHub Desktop.
Thanks for the suggestion. I needed to added the .group parameter because otherwise some functions like sum will perhaps not behave as intended. Interested to hear your thoughts.
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(rlang) | |
summarise_with <- function(.data, ..., .f, .with, .over, .group = TRUE, na.rm = TRUE) { | |
stopifnot(rlang::is_logical(.group)) | |
if(rlang::quo_is_symbol(rlang::enquo(.with))) { | |
.with <- rlang::enquo(.with) | |
} else { | |
.with <- rlang::sym(.with) | |
} | |
if(rlang::quo_is_symbol(rlang::enquo(.over))) { | |
.over <- rlang::enquo(.over) | |
} else { | |
.over <- rlang::sym(.over) | |
} | |
if (.group == TRUE) { | |
.data %>% | |
dplyr::group_by(..., !!.over) %>% | |
dplyr::summarise("{{.f}}_{{.with}}" := .f(!!.with, na.rm = na.rm)) | |
} else { | |
.data %>% | |
dplyr::group_by(...) %>% | |
dplyr::summarise("{{.f}}_{{.over}}" := .f(!!.over, !!.with, na.rm = na.rm)) | |
} | |
} | |
add_share_with <- function(.data, ..., .with, na.rm = TRUE) { | |
if(rlang::quo_is_symbol(rlang::enquo(.with))) { | |
.with <- rlang::enquo(.with) | |
} else { | |
.over <- rlang::sym(.with) | |
} | |
.data %>% | |
dplyr::group_by(...) %>% | |
dplyr::mutate("share_{{.with}}" := !!.with / sum(!!.with, na.rm = na.rm)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment