2024-11-27 09:56:06 +01:00
|
|
|
#' 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()].
|
2024-11-27 09:56:06 +01:00
|
|
|
#'
|
|
|
|
#' @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")
|
|
|
|
}
|
2024-11-27 09:56:06 +01:00
|
|
|
|
|
|
|
#' @rdname fct_drop
|
|
|
|
#' @export
|
2024-12-19 21:12:56 +01:00
|
|
|
#'
|
|
|
|
#' @examples
|
|
|
|
#' mtcars |>
|
|
|
|
#' numchar2fct() |>
|
|
|
|
#' fct_drop()
|
2024-11-27 09:56:06 +01:00
|
|
|
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)) {
|
2024-11-27 09:56:06 +01:00
|
|
|
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, ...)
|
|
|
|
}
|