Skip to content

Commit

Permalink
capture more exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
strengejacke committed Dec 18, 2023
1 parent 18f1ab0 commit b9f83ba
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 4 deletions.
2 changes: 1 addition & 1 deletion R/to_numeric.R
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ to_numeric.factor <- function(x,
}
out <- .set_back_labels(as.numeric(as.character(x)), x, reverse_values = FALSE)
} else {
out <- .set_back_labels(as.numeric(x), x, , reverse_values = FALSE)
out <- .set_back_labels(as.numeric(x), x, reverse_values = FALSE)
}

# shift to requested starting value
Expand Down
12 changes: 11 additions & 1 deletion R/utils_labels.R
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,17 @@
attr(new, "labels") <- stats::setNames(rev(labels), names(labels))
} else {
# keep value oder? Used for "to_numeric()"
attr(new, "labels") <- stats::setNames(labels, names(labels))
if (is.numeric(new)) {
if (any(grepl("[^0-9]", labels))) {
# if we have any non-numeric characters, convert to numeric
attr(new, "labels") <- stats::setNames(as.numeric(as.factor(labels)), names(labels))
} else {
# if we have numeric, or "numeric character" (like "1", "2", "3" etc.)
attr(new, "labels") <- stats::setNames(as.numeric(labels), names(labels))
}
} else {
attr(new, "labels") <- stats::setNames(labels, names(labels))
}
}
} else if (isFALSE(include_values)) {
attr(new, "labels") <- NULL
Expand Down
18 changes: 16 additions & 2 deletions tests/testthat/test-data_to_numeric.R
Original file line number Diff line number Diff line change
Expand Up @@ -197,12 +197,26 @@ test_that("to_numeric preserves correct label order", {
out <- to_numeric(x, dummy_factors = FALSE)
expect_identical(
attributes(out)$labels,
c(one = "1", two = "2", three = "3", four = "4")
c(one = 1, two = 2, three = 3, four = 4)
)
# correctly reverse scale
out <- to_numeric(reverse_scale(x), dummy_factors = FALSE)
expect_identical(
attributes(out)$labels,
c(one = "4", two = "3", three = "2", four = "1")
c(one = 4, two = 3, three = 2, four = 1)
)
# factor with alphabetical values
x <- factor(letters[1:4])
x <- assign_labels(x, values = c("one", "two", "three", "four"))
out <- to_numeric(x, dummy_factors = FALSE)
expect_identical(
attributes(out)$labels,
c(one = 1, two = 2, three = 3, four = 4)
)
# correctly reverse scale
out <- to_numeric(reverse_scale(x), dummy_factors = FALSE)
expect_identical(
attributes(out)$labels,
c(one = 4, two = 3, three = 2, four = 1)
)
})

0 comments on commit b9f83ba

Please sign in to comment.