R/tidy_ard_order.R

Defines functions tidy_ard_row_order tidy_ard_column_order

Documented in tidy_ard_column_order tidy_ard_row_order

#' Standard Order of ARD
#'
#' @description
#' ARD functions for relocating columns and rows to the standard order.
#'
#' - `tidy_ard_column_order()` relocates columns of the ARD to the standard order.
#'
#' - `tidy_ard_row_order()` orders rows of ARD according to variables, groups, and
#'   strata, while retaining the order of the input ARD.
#'
#' @param x (`data.frame`)\cr
#'   an ARD data frame of class 'card'
#'
#' @return an ARD data frame of class 'card'
#' @name tidy_ard_order
#'
#' @examples
#' # order columns
#' ard <-
#'   dplyr::bind_rows(
#'     ard_continuous(mtcars, variables = "mpg"),
#'     ard_continuous(mtcars, variables = "mpg", by = "cyl")
#'   )
#'
#' tidy_ard_column_order(ard) |>
#'   tidy_ard_row_order()
NULL

#' @rdname tidy_ard_order
#' @export
tidy_ard_column_order <- function(x) {
  set_cli_abort_call()

  group_cols <- dplyr::select(x, all_ard_groups()) |>
    names() |>
    sort()

  dplyr::select(
    x,
    all_of(group_cols),
    all_ard_variables(),
    any_of(c(
      "context",
      "stat_name", "stat_label", "stat", "stat_fmt", "fmt_fn",
      "warning", "error"
    )),
    dplyr::everything()
  )
}


#' @rdname tidy_ard_order
#' @export
tidy_ard_row_order <- function(x) {
  set_cli_abort_call()

  check_class(x, cls = "card")

  # get columns that dictate ordering
  cols <- x |>
    dplyr::select(
      all_ard_variables("names"),
      all_ard_groups("names"),
      all_ard_groups("levels")
    ) |>
    names()

  # perform the ordering
  x |> dplyr::arrange(across(all_of(cols), .fns = function(x) match(x, unique(x))))
}

Try the cards package in your browser

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

cards documentation built on Oct. 4, 2024, 1:09 a.m.