Skip to content

Commit

Permalink
Preserve attributes for "convert_to_na(drop_levels = TRUE)" (#472)
Browse files Browse the repository at this point in the history
  • Loading branch information
strengejacke committed Dec 13, 2023
1 parent 700243d commit 5f5c9c1
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 1 deletion.
2 changes: 1 addition & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
@@ -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", , "[email protected]", role = "aut",
comment = c(ORCID = "0000-0003-1995-6531", Twitter = "@patilindrajeets")),
Expand Down
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions R/convert_to_na.R
Original file line number Diff line number Diff line change
Expand Up @@ -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]
}
Expand Down
4 changes: 4 additions & 0 deletions tests/testthat/test-attributes.R
Original file line number Diff line number Diff line change
Expand Up @@ -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")
})


Expand Down

0 comments on commit 5f5c9c1

Please sign in to comment.