Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserve attributes for "convert_to_na(drop_levels = TRUE)" #472

Merged
merged 1 commit into from
Dec 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading