From 5f5c9c1536376a33d173408100e3f2b6b41f8c17 Mon Sep 17 00:00:00 2001 From: Daniel Date: Wed, 13 Dec 2023 14:30:51 +0100 Subject: [PATCH] Preserve attributes for "convert_to_na(drop_levels = TRUE)" (#472) --- DESCRIPTION | 2 +- NEWS.md | 2 ++ R/convert_to_na.R | 4 ++++ tests/testthat/test-attributes.R | 4 ++++ 4 files changed, 11 insertions(+), 1 deletion(-) diff --git a/DESCRIPTION b/DESCRIPTION index 6b743b4ea..7d8051b0e 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Type: Package Package: datawizard Title: Easy Data Wrangling and Statistical Transformations -Version: 0.9.0.5 +Version: 0.9.0.6 Authors@R: c( person("Indrajeet", "Patil", , "patilindrajeet.science@gmail.com", role = "aut", comment = c(ORCID = "0000-0003-1995-6531", Twitter = "@patilindrajeets")), diff --git a/NEWS.md b/NEWS.md index e2f2ecdff..9242a0913 100644 --- a/NEWS.md +++ b/NEWS.md @@ -12,6 +12,8 @@ BUG FIXES * `to_numeric()` now correctly deals with inversed factor levels when `preserve_levels = TRUE`. +* `convert_to_na()` now preserves attributes for factors when `drop_levels = TRUE`. + # datawizard 0.9.0 NEW FUNCTIONS diff --git a/R/convert_to_na.R b/R/convert_to_na.R index 116c71c35..0e95b7c5f 100644 --- a/R/convert_to_na.R +++ b/R/convert_to_na.R @@ -105,7 +105,11 @@ convert_to_na.factor <- function(x, na = NULL, drop_levels = FALSE, verbose = TR # drop unused labels value_labels <- attr(x, "labels", exact = TRUE) if (is.factor(x) && isTRUE(drop_levels)) { + # save label attribute + variable_label <- attr(x, "label", exact = TRUE) x <- droplevels(x) + # droplevels() discards attributes, so we need to re-assign them + attr(x, "label") <- variable_label } attr(x, "labels") <- value_labels[!value_labels %in% na] } diff --git a/tests/testthat/test-attributes.R b/tests/testthat/test-attributes.R index 4eb261a0e..2fc88ecc9 100644 --- a/tests/testthat/test-attributes.R +++ b/tests/testthat/test-attributes.R @@ -123,6 +123,10 @@ test_that("convert_to_na, attributes preserved", { attr(x, "myattri") <- "I'm here" x2 <- convert_to_na(x, na = 2, verbose = FALSE) expect_identical(attr(x2, "myattri", exact = TRUE), "I'm here") + # label attribute is preserved + attr(x$Species, "label") <- "Species Variable" + x2 <- convert_to_na(x, na = "setosa", drop_levels = TRUE, verbose = FALSE) + expect_identical(attributes(x$Species)$label, "Species Variable") })