Skip to content

Commit

Permalink
as_factor() should convert ordered factors to plain factors (#237)
Browse files Browse the repository at this point in the history
Fixes #216
  • Loading branch information
robinsones authored Jan 31, 2020
1 parent 5c6aabe commit 21aba84
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -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)
Expand Down
7 changes: 6 additions & 1 deletion R/as_factor.R
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions tests/testthat/test-as_factor.R
Original file line number Diff line number Diff line change
Expand Up @@ -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")
})

0 comments on commit 21aba84

Please sign in to comment.