From 9cae725de28fe4d0d5ceb1d45507866190bb70b7 Mon Sep 17 00:00:00 2001 From: Andreas Gammelgaard Damsbo Date: Wed, 27 Nov 2024 09:56:06 +0100 Subject: [PATCH] extension to forcats::fct_drop to perform across data.frame --- R/fct_drop.R | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 R/fct_drop.R diff --git a/R/fct_drop.R b/R/fct_drop.R new file mode 100644 index 0000000..2f84e0d --- /dev/null +++ b/R/fct_drop.R @@ -0,0 +1,29 @@ +#' Drop unused levels preserving label data +#' +#' This extends [forcats::fct_drop()] to natively work across a data.frame and +#' replace [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 +NULL + +#' @rdname fct_drop +#' @export +fct_drop.data.frame <- function(x, ...) { + purrr::map(\(.x){ + if (is.factor(.x)){ + forcats::fct_drop(.x) + } else { + .x + } + }) |> + dplyr::bind_cols() +} + + +