From 21aba84699470c08c9d76fc0389b44fbf03c9b8b Mon Sep 17 00:00:00 2001 From: Emily Robinson Date: Fri, 31 Jan 2020 11:50:55 -0800 Subject: [PATCH] `as_factor()` should convert ordered factors to plain factors (#237) Fixes #216 --- NEWS.md | 2 ++ R/as_factor.R | 7 ++++++- tests/testthat/test-as_factor.R | 6 ++++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/NEWS.md b/NEWS.md index b5d5615a..b2e63e63 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,7 @@ # forcats (development version) +* `as_factor()` converts ordered factor into plain factor (@robinson_es, #216). + * `first2()`, a `fct_reorder2()` helper function, sorts `.y` by the first value of `.x` (@jtr13). * fixed bug in `fct_collapse()` so it now correctly collapses factors when `group_other = TRUE` (#172), and makes `"Other"` the last level (#202) (@gtm19, #172 & #202) diff --git a/R/as_factor.R b/R/as_factor.R index 74337538..d46b5bab 100644 --- a/R/as_factor.R +++ b/R/as_factor.R @@ -34,7 +34,12 @@ as_factor <- function(x, ...) { #' @rdname as_factor #' @export as_factor.factor <- function(x, ...) { - x + structure( + x, + class = "factor", + label = attr(x, "label", exact = TRUE), + levels = attr(x, "levels", exact = TRUE) + ) } #' @rdname as_factor diff --git a/tests/testthat/test-as_factor.R b/tests/testthat/test-as_factor.R index abeae50b..d6b4ba35 100644 --- a/tests/testthat/test-as_factor.R +++ b/tests/testthat/test-as_factor.R @@ -16,3 +16,9 @@ test_that("supports NA (#89)", { x <- c("a", "z", "g", NA) expect_equal(as_factor(x), fct_inorder(x)) }) + +test_that("converts ordered factor into plain factor (#216)", { + x <- factor(c("a", "z", "g"), ordered = TRUE) + x <- as_factor(x) + expect_s3_class(as_factor(x), "factor", exact = "TRUE") +})