diff --git a/NEWS.md b/NEWS.md index e0e07694..317e27d7 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,8 @@ # forcats (development version) +* `fct_other()` no longer generates a warning if no levels are replaced with + other (#265). + # forcats 0.5.2 * New `fct()` which works like `factor()` but errors if values of `x` diff --git a/R/other.R b/R/other.R index d32e14d1..2f365588 100644 --- a/R/other.R +++ b/R/other.R @@ -25,6 +25,10 @@ fct_other <- function(f, keep, drop, other_level = "Other") { levels[levels %in% drop] <- other_level } + if (!other_level %in% levels) { + return(f) + } + f <- lvls_revalue(f, levels) fct_relevel(f, other_level, after = Inf) } diff --git a/tests/testthat/test-other.R b/tests/testthat/test-other.R index 0ad6073e..017a4be5 100644 --- a/tests/testthat/test-other.R +++ b/tests/testthat/test-other.R @@ -13,6 +13,11 @@ test_that("drops levels in drop", { expect_equal(levels(x2), c("b", "Other")) }) +test_that("works without warning if no levels replaced", { + x <- factor("a") + expect_no_warning(fct_other(x, keep = "a")) +}) + test_that("must supply exactly one of drop and keep", { f <- factor(c("a", "b"))