R/02_mutatex.R

#' mutate/transmute with grouping
#'
#' If \code{.by} is given, data is grouped just for mutate operation.
#'
#' Prefer standard grouping notation for a sequence of operations as it will
#' be more efficient, but for a single operation this is not a costly alternative.
#'
#' @inheritParams dplyr::mutate
#' @param .by a vector or list of variables as characters or given by \code{vars}
#' @param .keep if \code{"new"}, \code{transmute} will be called instead of \code{mutate}
#' @export
#' @examples
#' iris[c(1:2,51:52),] %>% mutatex(z= mean(Sepal.Length),.by= vars(Species))
#' iris[c(1:2,51:52),] %>% mutatex(z= mean(Sepal.Length),.by= "Species")
mutatex <- function(.data, ..., .by = NULL, .rowwise = FALSE, .keep = c("all","new"))
{
  # checks
  if (!is.null(.by) && .rowwise)
    stop("You can't use rowwise and .by at the same time")
  .keep <- match.arg(.keep)
  .by <- dplyr:::tbl_at_syms(.data, .by)
  if (!length(.by) && ! .rowwise)
    if (.keep == "all") dplyr::mutate(.data, ...) else
      dplyr::transmute(.data, ...)
  else  {
    groups <- dplyr::group_vars(.data)
    x <- if (.rowwise) dplyr::rowwise(.data) else dplyr::group_by(.data,!!!.by, add = TRUE)
    x <- if (.keep == "all") dplyr::mutate(x, ...) else dplyr::transmute(x, ...)
    x <- dplyr::group_by(x, !!!rlang::syms(groups), add = FALSE)
    x
  }
}
moodymudskipper/tidyx documentation built on May 17, 2019, 10:39 a.m.