Skip to content

Commit

Permalink
Preserve NAs in x when zero range
Browse files Browse the repository at this point in the history
  • Loading branch information
hadley committed Jul 23, 2015
1 parent cca879a commit b481ee2
Show file tree
Hide file tree
Showing 5 changed files with 14 additions and 4 deletions.
2 changes: 1 addition & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
Package: scales
Version: 0.2.5.9001
Version: 0.2.5.9002
Authors@R: c(
person("Hadley", "Wickham", , "hadley@rstudio.com", c("aut", "cre")),
person("RStudio", role = "cph")
Expand Down
3 changes: 3 additions & 0 deletions NEWS
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
Version 0.2.5.9000
------------------------------------------------------------------------------

* `rescale()` preserves missing values in input when the range of `x` is
(effectively) 0 (ggplot2#985).

* Continuous colour palettes now use `colour_ramp()` instead of `colorRamp()`.
This only supports interpolation in Lab colour space, but is hundreds of
times faster.
Expand Down
6 changes: 4 additions & 2 deletions R/bounds.r
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@
#' rescale(1:100)
#' rescale(runif(50))
#' rescale(1)
rescale <- function(x, to = c(0, 1), from = range(x, na.rm = TRUE)) {
if (zero_range(from) || zero_range(to)) return(rep(mean(to), length(x)))
rescale <- function(x, to = c(0, 1), from = range(x, na.rm = TRUE, finite = TRUE)) {
if (zero_range(from) || zero_range(to)) {
return(ifelse(is.na(x), NA, mean(to)))
}

(x - from[1]) / diff(from) * diff(to) + to[1]
}
Expand Down
2 changes: 1 addition & 1 deletion man/rescale.Rd
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
\alias{rescale}
\title{Rescale numeric vector to have specified minimum and maximum.}
\usage{
rescale(x, to = c(0, 1), from = range(x, na.rm = TRUE))
rescale(x, to = c(0, 1), from = range(x, na.rm = TRUE, finite = TRUE))
}
\arguments{
\item{x}{numeric vector of values to manipulate.}
Expand Down
5 changes: 5 additions & 0 deletions tests/testthat/test-rescale.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
context("rescale")

test_that("rescale preserves NAs even when x has zero range", {
expect_equal(rescale(c(1, NA)), c(0.5, NA))
})

0 comments on commit b481ee2

Please sign in to comment.