REDCapCAST/R/fct_drop.R

46 lines
861 B
R
Raw Permalink Normal View History

#' Drop unused levels preserving label data
#'
#' This extends [forcats::fct_drop()] to natively work across a data.frame and
2024-12-19 21:12:56 +01:00
#' replaces [base::droplevels()].
#'
#' @param x Factor to drop unused levels
#' @param ... Other arguments passed down to method.
#' @export
#'
#' @importFrom forcats fct_drop
#' @export
#' @name fct_drop
2024-12-19 21:12:56 +01:00
fct_drop <- function(x, ...) {
UseMethod("fct_drop")
}
#' @rdname fct_drop
#' @export
2024-12-19 21:12:56 +01:00
#'
#' @examples
#' mtcars |>
#' numchar2fct() |>
#' fct_drop()
fct_drop.data.frame <- function(x, ...) {
2024-11-27 15:49:45 +01:00
purrr::map(x, \(.x){
2024-12-19 21:12:56 +01:00
if (is.factor(.x)) {
forcats::fct_drop(.x)
} else {
.x
}
}) |>
dplyr::bind_cols()
}
2024-12-19 21:12:56 +01:00
#' @rdname fct_drop
#' @export
#'
#' @examples
#' mtcars |>
#' numchar2fct() |>
#' dplyr::mutate(vs = fct_drop(vs))
fct_drop.factor <- function(x, ...) {
forcats::fct_drop(f = x, ...)
}