Skip to content

Instantly share code, notes, and snippets.

@dholstius
Forked from dgrtwo/grouply.R
Last active Aug 31, 2016
Embed
What would you like to do?
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 24, 2016

Just trying this now but it looks pretty good to me- what's the problem?

@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