-
-
Save dholstius/71d6dcc1baa60969c0f73a4afcc5ce24 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
grouply <- function(f, ...) { | |
groups <- lazyeval::lazy_dots(...) | |
function(tbl, ...) { | |
dplyr::group_by_(tbl, .dots = groups) %>% | |
f(...) %>% | |
dplyr::ungroup() | |
} | |
} | |
mtcars %>% grouply(mutate, cyl, am)(n = n()) |
This file contains hidden or 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
#' Mutate within (transient) groups | |
#' | |
#' @params ... Variables to group by. See \link[dplyr]{group_by} for details. | |
#' @params .dots Used to work around non-standard evaluation. See \code{vignette("nse")} for details. | |
#' @params add See note below | |
#' | |
#' @return a function (wrapping \link[dplyr]{mutate_}) | |
#' | |
#' @note Should `add` default to `TRUE`? | |
#' @note Should we completely ungroup the result, | |
#' or restore the original grouping? | |
#' (as much as possible, if `add` = `FALSE`?) | |
#' | |
#' @importFrom dplyr group_by_ mutate_ | |
#' | |
#' @examples | |
#' library(dplyr) | |
#' mtcars %>% mutate_by(cyl, am)(n = n()) | |
#' mtcars %>% mutate_by_(.dots = c("cyl", "am"))(n = n()) | |
#' | |
#' @export | |
mutate_by <- function (..., add = TRUE) { | |
by_dots <- lazyeval::lazy_dots(...) | |
mutate_by_(.dots = by_dots, add = add) | |
} | |
#' @describeIn mutate_by | |
#' @export | |
mutate_by_ <- function (..., .dots, add = TRUE) { | |
all_by_dots <- lazyeval::all_dots(.dots, ..., all_named = TRUE) | |
function (.data, ..., .dots) { | |
grouped <- group_by_(.data, .dots = all_by_dots, add = add) | |
# why u no work? | |
# mutations <- lazyeval::all_dots(..., .dots) | |
mutations <- lazyeval::lazy_dots(...) | |
mutated <- mutate_(grouped, .dots = mutations) | |
group_by_(mutated, .dots = as.character(groups(.data))) # restore grouping of .data | |
} | |
} | |
if (interactive()) { | |
mtcars %>% mutate_by_("cyl", "am")(n = n(), .dots = c(foo = "bar")) | |
mtcars %>% mutate_by(cyl, am)(n = n()) | |
} |
Upon some consideration, I realized there's another useful "preposition" here: where
. mutate_where
would be handy and reduce the need for ifelse
, and this question lays out a need for summarise_where
, though I'm not quite as sold on it.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just trying this now but it looks pretty good to me- what's the problem?