Skip to content

Commit

Permalink
fix in recode.haven_labelled() (#152)
Browse files Browse the repository at this point in the history
* fix in `recode.haven_labelled()`

when `.x` contains `NA` and `.combine_value_labels = TRUE`

fix #151

* additinal test
  • Loading branch information
larmarange authored Aug 31, 2023
1 parent e908107 commit 035ad29
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 2 deletions.
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

* avoid an error with `print.look_for()` when console pane is physically shrunk
too small (#148)
* fix in `recode.haven_labelled()` when `.x` contains `NA` and
`.combine_value_labels = TRUE` (#151)

# labelled 2.12.0

Expand Down
4 changes: 2 additions & 2 deletions R/recode.R
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,10 @@ recode.haven_labelled <- function(
if (.combine_value_labels) {
ret <- copy_labels(.x, ret)

old_vals <- unique(.x)
old_vals <- unique(.x) %>% na.omit()
new_vals <- c()
for (o in old_vals) {
new_vals <- c(new_vals, ret[.x == o][1])
new_vals <- c(new_vals, ret[!is.na(.x) & .x == o][1])
}

original_labels <- val_labels(.x)
Expand Down
11 changes: 11 additions & 0 deletions tests/testthat/test-labelled.r
Original file line number Diff line number Diff line change
Expand Up @@ -892,6 +892,17 @@ test_that("dplyr::recode could be applied to character labelled vector", {
expect_equal(x, labelled(c("a", "b", "b"), c(yes = "a", no = "b")))
})

test_that("dplyr::recode could handle NA with .combine_value_labels", {
x <- labelled(c(NA, 1:3), c(yes = 1, maybe = 2, no = 3))
y <- x %>% dplyr::recode(`2` = 0L, .combine_value_labels = TRUE)
expect_true(all(c(0, 1, 3) %in% val_labels(y)))

y <- x %>% dplyr::recode(`2` = 0L, `3` = 0L, .combine_value_labels = TRUE)
expect_true(all(c(0, 1) %in% val_labels(y)))
expect_equal(val_label(y, 0), "maybe / no")
})


# update_labelled ----------------------------------------

test_that("update_labelled update previous haven's labelled objects but not Hmisc's labelled objects", { # nolint
Expand Down

0 comments on commit 035ad29

Please sign in to comment.