Skip to content

Commit

Permalink
train_continuous now preserves the class of the input (#167)
Browse files Browse the repository at this point in the history
Fixes #166
  • Loading branch information
billdenney authored and hadley committed Sep 7, 2018
1 parent bcf76e6 commit 2ccb2fb
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 6 additions & 1 deletion R/scale-continuous.r
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
37 changes: 37 additions & 0 deletions tests/testthat/test-scale.r
Original file line number Diff line number Diff line change
Expand Up @@ -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)
)
})

0 comments on commit 2ccb2fb

Please sign in to comment.