fct_drop refined

This commit is contained in:
Andreas Gammelgaard Damsbo 2024-12-19 21:12:56 +01:00
commit 7d82eeebd4
No known key found for this signature in database
8 changed files with 92 additions and 17 deletions

View file

@ -1,7 +1,7 @@
#' Drop unused levels preserving label data
#'
#' This extends [forcats::fct_drop()] to natively work across a data.frame and
#' replace [base::droplevels()].
#' replaces [base::droplevels()].
#'
#' @param x Factor to drop unused levels
#' @param ... Other arguments passed down to method.
@ -10,13 +10,20 @@
#' @importFrom forcats fct_drop
#' @export
#' @name fct_drop
NULL
fct_drop <- function(x, ...) {
UseMethod("fct_drop")
}
#' @rdname fct_drop
#' @export
#'
#' @examples
#' mtcars |>
#' numchar2fct() |>
#' fct_drop()
fct_drop.data.frame <- function(x, ...) {
purrr::map(x, \(.x){
if (is.factor(.x)){
if (is.factor(.x)) {
forcats::fct_drop(.x)
} else {
.x
@ -26,4 +33,13 @@ fct_drop.data.frame <- function(x, ...) {
}
#' @rdname fct_drop
#' @export
#'
#' @examples
#' mtcars |>
#' numchar2fct() |>
#' dplyr::mutate(vs = fct_drop(vs))
fct_drop.factor <- function(x, ...) {
forcats::fct_drop(f = x, ...)
}