Skip to content

Instantly share code, notes, and snippets.

@maurolepore
Forked from vintented/summarise_with.R
Created August 17, 2020 16:33
Show Gist options
  • Save maurolepore/8692696f5df472814a739e60eeebbe56 to your computer and use it in GitHub Desktop.
Save maurolepore/8692696f5df472814a739e60eeebbe56 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.
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