R/10_mutate_summarize_helpers.R

# @export
.at <- function(.vars, .funs, ...) {
  in_a_piped_fun <- exists(".",parent.frame()) &&
    length(ls(envir=parent.frame(), all.names = TRUE)) == 1
  if (!in_a_piped_fun)
    stop(".at() must be called as an argument to a piped function")
  .tbl <- try(eval.parent(quote(.)))
  dplyr:::manip_at(
    .tbl, .vars, .funs, rlang::enquo(.funs), rlang:::caller_env(),
    .include_group_vars = TRUE, ...)
}

# @export
.if <- function(.predicate, .funs, ...) {
  in_a_piped_fun <- exists(".",parent.frame()) &&
    length(ls(envir=parent.frame(), all.names = TRUE)) == 1
  if (!in_a_piped_fun)
    stop(".if() must be called as an argument to a piped function")
  .tbl <- try(eval.parent(quote(.)))
  dplyr:::manip_if(
    .tbl, .predicate, .funs, rlang::enquo(.funs), caller_env(),
    .include_group_vars = TRUE, ...)
}

# @export
call_at <- function(.funs, ...){
  in_a_piped_fun <- exists(".",parent.frame()) &&
    length(ls(envir = parent.frame(), all.names = TRUE)) == 1
  if (!in_a_piped_fun)
    stop("call_at() must be called as an argument to a piped function")
  .tbl <- try(eval.parent(quote(.)))
  .vars <- unname(dplyr::select_vars(names(.tbl), !!!rlang::quos(...)))
  dplyr:::manip_at(
    .tbl, .vars, .funs, rlang::enquo(.funs), rlang:::caller_env(),
    .include_group_vars = TRUE)
}

#mtcars %>%
#  group_by(cyl) %>% summarize(
#    !!!.at(c("mpg","disp"),list(mean = ~mean(.))),
#    !!!.at(c(HP="hp","drat"),median),
#    !!!.if(~.[1]==4,first),
#    !!!call_at(funs(min,max), matches("q|w")),
#    max_wt = max(wt))

# # A tibble: 3 x 12
#     cyl mpg_mean disp_mean    HP  drat  gear  carb wt_min qsec_min wt_max qsec_max max_wt
#   <dbl>    <dbl>     <dbl> <dbl> <dbl> <dbl> <dbl>  <dbl>    <dbl>  <dbl>    <dbl>  <dbl>
# 1     4     26.7      105.   91   4.08     4     1   1.51     16.7   3.19     22.9   3.19
# 2     6     19.7      183.  110   3.9      4     4   2.62     15.5   3.46     20.2   3.46
# 3     8     15.1      353.  192.  3.12     3     2   3.17     14.5   5.42     18     5.42
moodymudskipper/tidyx documentation built on May 17, 2019, 10:39 a.m.