#' summarize with grouping
#'
#' If \code{.by} is given, data is grouped just for summarize operation.
#'
#' Prefer standard grouping notation for a sequence of operations.
#'
#' @inheritParams dplyr::summarize
#' @param .by a vector or list of variables as characters or given by \code{vars}
#'
#' @export
#'
#' @examples
#' iris[c(1:2,51:52),] %>% summarizex(z= mean(Sepal.Length),.by= vars(Species))
#' iris[c(1:2,51:52),] %>% summarizex(z= mean(Sepal.Length),.by= "Species")
summarizex <- function(.data, ..., .by = NULL, .unnest = TRUE)
{
# store names of by calls that were not created with an explicit name
# they will be removed in the ends
tmp_by_cols <- get_tmp_by_cols(.data, .by)
if(is.character(by))
by <- dplyr:::tbl_at_syms(data, by)
#if (identical(rlang::enquo(.by)[[2]], quote(NULL))) x <- dplyr::summarize(.data, ...)
if(is.null(by))
x <- dplyr::summarize(.data, ...)
else {
groups <- dplyr::group_vars(.data)
x <- dplyr::group_by(.data,!!!.by, add = TRUE)
x <- dplyr::summarize(x, ...)
x <- dplyr::group_by(x, !!!rlang::syms(groups), add = FALSE)
# remove temporary by cols
if (length(tmp_by_cols)) x <- select(x,-!!sym(tmp_by_cols))
}
if (.unnest && "list" %in% purrr::map_chr(x,typeof)) tidyr::unnest(x) else x
}
#' @export
at <- function(.vars, .fun, .key = "data"){
eval.parent(list(map_dfc(.vars,.fun)))
}
# mtcars %>%
# group_by(cyl) %>%
# summarizex(at(lst(mpg, disp, hp, drat),mean),
# wt = max(wt))
#
# mtcars %>%
# summarizex(at(lst(mpg, disp, hp, drat),mean), wt = max(wt), .by = "cyl")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.