# Standalone file: do not edit by hand
# Source: https://github.com/insightsengineering/standalone/blob/HEAD/R/standalone-forcats.R
# Generated by: usethis::use_standalone("insightsengineering/standalone", "forcats")
# ----------------------------------------------------------------------
#
# ---
# repo: insightsengineering/standalone
# file: standalone-forcats.R
# last-updated: 2025-05-03
# license: https://unlicense.org
# imports:
# ---
#
# This file provides a minimal shim to provide a forcats-like API on top of
# base R functions. They are not drop-in replacements but allow a similar style
# of programming.
#
# ## Changelog
# 2025-05-03
#   - `add fct_relevel()` fix for non-factor inputs
# 2025-02-24
#   - `add fct_relevel()` function.
#
# nocov start
# styler: off

fct_infreq <- function(f, ordered = NA) {
  # reorder by frequency
  factor(
    f,
    levels = table(f) |> sort(decreasing = TRUE) |> names(),
    ordered = ifelse(is.na(ordered), is.ordered(f), ordered)
  )
}

fct_inorder <- function(f, ordered = NA) {
  factor(
    f,
    levels = stats::na.omit(unique(f)) |> union(levels(f)),
    ordered = ifelse(is.na(ordered), is.ordered(f), ordered)
  )
}

fct_rev <- function(f) {
  if (!inherits(f, "factor")) f <- factor(f)

  factor(
    f,
    levels = rev(levels(f)),
    ordered = is.ordered(f)
  )
}

fct_expand <- function(f, ..., after = Inf) {
  if (!inherits(f, "factor")) f <- factor(f)

  old_levels <- levels(f)
  new_levels <-
    old_levels |>
    append(values = setdiff(c(...), old_levels), after = after)
  factor(f, levels = new_levels)
}

fct_na_value_to_level <- function(f, level = NA) {
  if (!inherits(f, "factor")) f <- factor(f)

  # make NA an explicit level
  f <- addNA(f, ifany = FALSE)

  # replace NA level with the string passed in `level` argument
  if (!is.na(level)) levels(f)[is.na(levels(f))] <- level

  f
}


fct_relevel <- function(f, ..., after = 0L) {
  if (!inherits(f, "factor")) f <- as.factor(f)
  old_levels <- levels(f)
  # Handle re-leveling function or specified levels
  first_levels <- if (rlang::dots_n(...) == 1L && (is.function(..1) || rlang::is_formula(..1))) {
    fun <- rlang::as_function(..1)
    fun(old_levels)
  } else {
    rlang::chr(...)
  }

  # Reorder levels
  new_levels <- append(setdiff(old_levels, first_levels), first_levels, after = after)
  new_factor <- factor(f, levels = new_levels)
  return(new_factor)
}

# nocov end
# styler: on
