Skip to content

Commit

Permalink
Properly fix #383
Browse files Browse the repository at this point in the history
  • Loading branch information
thomasp85 committed Nov 1, 2023
1 parent 432432e commit 01493b7
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 3 deletions.
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
(@teunbrand, #369).
* Training on factor data no longer sorts the range after multiple training
passes (#383)
* Attempt to make the sort behavior of the range consistent for character
vectors during training. Mixing of character and factor data will still lead
to different results depending on the training order.

# scales 1.2.1

Expand Down
11 changes: 8 additions & 3 deletions R/scale-discrete.R
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,16 @@ train_discrete <- function(new, existing = NULL, drop = FALSE, na.rm = FALSE) {
}

discrete_range <- function(old, new, drop = FALSE, na.rm = FALSE) {
is_factor <- is.factor(new) || is.factor(old)
new <- clevels(new, drop = drop, na.rm = na.rm)
if (is.null(old)) {
return(new)
}
if (!is.character(old)) old <- clevels(old, na.rm = na.rm)
if (!is.character(old)) {
old <- clevels(old, na.rm = na.rm)
} else {
old <- sort(old, na.last = if (na.rm) NA else TRUE)
}

new_levels <- setdiff(new, as.character(old))

Expand All @@ -53,10 +58,10 @@ discrete_range <- function(old, new, drop = FALSE, na.rm = FALSE) {

# Avoid sorting levels when dealing with factors to mimick behaviour of
# clevels()
if (is.factor(new)) {
if (is_factor) {
return(range)
}
sort(range)
sort(range, na.last = if (na.rm) NA else TRUE)
}

clevels <- function(x, drop = FALSE, na.rm = FALSE) {
Expand Down
1 change: 1 addition & 0 deletions tests/testthat/test-range.R
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,5 @@ test_that("factor discrete ranges stay in order", {
expect_equal(discrete_range(f, f), letters[3:1])
expect_equal(discrete_range(f, "c"), letters[3:1])
expect_equal(discrete_range(f, c("a", "b", "c")), letters[3:1])
expect_equal(discrete_range(f, c("a", "b", "c", NA), na.rm = FALSE), letters[3:1])
})

0 comments on commit 01493b7

Please sign in to comment.