Skip to content

Instantly share code, notes, and snippets.

@dholstius
Forked from dgrtwo/grouply.R
Last active August 31, 2016 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dholstius/71d6dcc1baa60969c0f73a4afcc5ce24 to your computer and use it in GitHub Desktop.
Save dholstius/71d6dcc1baa60969c0f73a4afcc5ce24 to your computer and use it in GitHub Desktop.
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())
#' 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())
}
@dgrtwo
Copy link

dgrtwo commented Aug 31, 2016

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