Skip to content

Commit 49b8936

Browse files
committed
preserve subclasses as well as attrs in refactor fn #83
1 parent 6a9bd65 commit 49b8936

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

R/lvls.R

+11
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,17 @@ refactor <- function(f, new_levels, ordered = NA) {
9595

9696
new_f <- factor(f, levels = new_levels, exclude = NULL, ordered = ordered)
9797
attributes(new_f) <- utils::modifyList(attributes(f), attributes(new_f))
98+
99+
if (is.ordered(f) && !is.ordered(new_f)) {
100+
idx <- match("ordered", class(f))
101+
class(new_f) <- class(f)[-idx]
102+
} else if (!is.ordered(f) && is.ordered(new_f)) {
103+
idx <- match("factor", class(f))
104+
class(new_f) <- append(class(f), "ordered", after = idx - 1)
105+
} else {
106+
class(new_f) <- class(f)
107+
}
108+
98109
new_f
99110
}
100111

tests/testthat/test-lvls.R

+33
Original file line numberDiff line numberDiff line change
@@ -80,3 +80,36 @@ test_that("can change ordered status of output", {
8080
expect_equal(is.ordered(lvls_reorder(f2, 1:3, ordered = FALSE)), FALSE)
8181
expect_equal(is.ordered(lvls_reorder(f2, 1:3, ordered = TRUE)), TRUE)
8282
})
83+
84+
# refactor ------------------------------------------------------------
85+
86+
test_that("preserves attributes", {
87+
f1 <- factor(letters[1:3])
88+
attr(f1, "foo") <- "bar"
89+
90+
f2 <- refactor(f1, letters[1:4])
91+
92+
expect_equal(attr(f1, "foo"), attr(f2, "foo"))
93+
})
94+
95+
test_that("preserves s3 subclasses", {
96+
f1 <- factor(letters[1:3])
97+
class(f1) <- c("foo", class(f1))
98+
99+
f2 <- refactor(f1, letters[1:4])
100+
101+
expect_equal(class(f1), class(f2))
102+
})
103+
104+
test_that("preserves s3 subclasses when toggling ordered", {
105+
f1 <- factor(letters[1:3])
106+
class(f1) <- c("foo", class(f1))
107+
108+
f2 <- refactor(f1, letters[1:4], ordered = TRUE)
109+
110+
expect_equal(class(f2), c("foo", "ordered", "factor"))
111+
112+
f3 <- refactor(f2, letters[1:3], ordered = FALSE)
113+
114+
expect_equal(class(f3), c("foo", "factor"))
115+
})

0 commit comments

Comments
 (0)