R/group_split.R

Defines functions tt_group_split group_split. group_split

Documented in group_split group_split.

#' Split data frame by groups
#'
#' @description
#' Split data frame by groups. Returns a list.
#'
#' @param .df A data.frame or data.table
#' @param ... Columns to group and split by. `tidyselect` compatible.
#' @param .keep Should the grouping columns be kept
#' @param .named _experimental_: Should the list be named with labels that identify the group
#'
#' @export
#'
#' @examples
#' df <- tidytable(
#'   a = 1:3,
#'   b = 1:3,
#'   c = c("a", "a", "b"),
#'   d = c("a", "a", "b")
#' )
#'
#' df %>%
#'   group_split(c, d)
#'
#' df %>%
#'   group_split(c, d, .keep = FALSE)
#'
#' df %>%
#'   group_split(c, d, .named = TRUE)
group_split <- function(.df, ..., .keep = TRUE, .named = FALSE) {
  .df <- .df_as_tidytable(.df)

  if (is_ungrouped(.df)) {
    tt_group_split(.df, ..., .keep = .keep, .named = .named)
  } else {
    .by <- group_vars(.df)
    out <- ungroup(.df)
    tt_group_split(out, all_of(.by), .keep = .keep, .named = .named)
  }
}

#' @export
#' @keywords internal
#' @inherit group_split
group_split. <- function(.df, ..., .keep = TRUE, .named = FALSE) {
  deprecate_dot_fun()
  group_split(.df, ..., .keep = .keep, .named = .named)
}

tt_group_split <- function(.df, ..., .keep = TRUE, .named = FALSE) {
  by <- select(.df, ...)

  if (is_false(.keep)) {
    .df <- select(.df, -all_of(names(by)))
  }

  split <- vec_split(.df, by)

  out <- split$val

  if (is_true(.named)) {
    names <- exec(paste, !!!split$key, sep = "_")
    names(out) <- names
  }

  out
}

Try the tidytable package in your browser

Any scripts or data that you put into this service are public.

tidytable documentation built on Oct. 5, 2023, 5:07 p.m.