R/05_slicex.R

#' slice 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::slice
#' @param .by a vector or list of variables as characters or given by \code{vars}
#'
#' @export
#'
#' @examples
#' iris %>% slicex(1:2, .by= vars(Species))
slicex <- function (.data, ..., .by)
{

  # 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)

  .by <- dplyr:::tbl_at_syms(.data, .by)
  if (identical(rlang::enquo(.by)[[2]], quote(NULL))) {
   x <- dplyr::slice(.data, ...)
  } else  {
    groups <- dplyr::group_vars(.data)
    x <- dplyr::group_by(.data,!!!.by, add = TRUE)
    x <- dplyr::slice(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))
  }
  x
}
moodymudskipper/tidyx documentation built on May 17, 2019, 10:39 a.m.