From b9f83ba3ddb95d406951b9d7133da3fb46167811 Mon Sep 17 00:00:00 2001 From: Daniel Date: Mon, 18 Dec 2023 12:17:23 +0100 Subject: [PATCH] capture more exceptions --- R/to_numeric.R | 2 +- R/utils_labels.R | 12 +++++++++++- tests/testthat/test-data_to_numeric.R | 18 ++++++++++++++++-- 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/R/to_numeric.R b/R/to_numeric.R index 602891f70..8bfcac6bc 100644 --- a/R/to_numeric.R +++ b/R/to_numeric.R @@ -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 diff --git a/R/utils_labels.R b/R/utils_labels.R index 5bcebc80d..4b28ac778 100644 --- a/R/utils_labels.R +++ b/R/utils_labels.R @@ -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 diff --git a/tests/testthat/test-data_to_numeric.R b/tests/testthat/test-data_to_numeric.R index a170be60e..464c35e8d 100644 --- a/tests/testthat/test-data_to_numeric.R +++ b/tests/testthat/test-data_to_numeric.R @@ -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) ) })