diff --git a/NEWS.md b/NEWS.md index 494406a1..bf52403f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -32,6 +32,9 @@ * `log_breaks()` provides usable breaks even with very small ranges (@billdenney, #168) +* `train_continuous()` now maintains the class of inputs when they are not + numeric (@billdenney, #166). + # scales 1.0.0 ## New Features diff --git a/R/scale-continuous.r b/R/scale-continuous.r index 35690022..9fe6ca08 100644 --- a/R/scale-continuous.r +++ b/R/scale-continuous.r @@ -38,7 +38,12 @@ train_continuous <- function(new, existing = NULL) { if (is.factor(new) || !typeof(new) %in% c("integer", "double")) { stop("Discrete value supplied to continuous scale", call. = FALSE) } - suppressWarnings(range(existing, new, na.rm = TRUE, finite = TRUE)) + # range(NULL, x) strips attributes + if (is.null(existing)) { + suppressWarnings(range(new, na.rm = TRUE, finite = TRUE)) + } else { + suppressWarnings(range(existing, new, na.rm = TRUE, finite = TRUE)) + } } # Map values for a continuous palette. diff --git a/tests/testthat/test-scale.r b/tests/testthat/test-scale.r index ec680c1a..a88b1ec5 100644 --- a/tests/testthat/test-scale.r +++ b/tests/testthat/test-scale.r @@ -19,3 +19,40 @@ test_that("NA.value works for discrete", { expect_that(dscale(x, pal, "grey50")[1], equals("grey50")) expect_that(dscale(x, pal, "grey50")[5], equals("grey50")) }) + +test_that("train_continuous stops on discrete values", { + expect_error(train_continuous(LETTERS[1:5]), + regexp = "Discrete value supplied" + ) +}) + +test_that("train_continuous maintains class with `existing=NULL`.", { + expect_equal( + train_continuous(1:5), + c(1, 5) + ) + my_date <- as.POSIXct("2018-01-01") + expect_equal( + train_continuous(my_date), + c(my_date, my_date) + ) +}) + +test_that("train_continuous changes class to the class of `existing` when not NULL.", { + my_date <- as.POSIXct("2018-01-01") + expect_equal( + train_continuous(my_date, existing = 1), + c(1, my_date) + ) + expect_equal( + train_continuous(1, existing = my_date), + c(as.POSIXct(1, origin = "1970-01-01"), my_date) + ) +}) + +test_that("train_continuous with new=NULL maintains existing range.", { + expect_equal( + train_continuous(NULL, existing = c(1, 5)), + c(1, 5) + ) +})