Skip to content

Commit 014f099

Browse files
AdamK-AAdamK-A
AdamK-A
authored and
AdamK-A
committed
Fixed factor cross ordering
1 parent 6a9bd65 commit 014f099

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

DESCRIPTION

+1-1
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,4 @@ Config/testthat/edition: 3
3838
Encoding: UTF-8
3939
LazyData: true
4040
Roxygen: list(markdown = TRUE)
41-
RoxygenNote: 7.2.3
41+
RoxygenNote: 7.3.2

R/cross.R

+2-1
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@ fct_cross <- function(..., sep = ":", keep_empty = FALSE) {
3232
newf <- exec(paste, !!!.data, sep = sep)
3333

3434
old_levels <- lapply(.data, levels)
35-
grid <- exec(expand.grid, old_levels)
35+
grid_unsorted <- exec(expand.grid, old_levels)
36+
grid <- grid_unsorted[do.call(order, grid_unsorted), ]
3637
new_levels <- exec(paste, !!!grid, sep = sep)
3738

3839
if (!keep_empty) {

tests/testthat/test-cross.R

+20
Original file line numberDiff line numberDiff line change
@@ -71,3 +71,23 @@ test_that("validates its inputs", {
7171
fct_cross("x", keep_empty = 1)
7272
})
7373
})
74+
75+
test_that("Cross factoring 2 levels in order", {
76+
f1 <- fct_inorder(c("a4", "a3", "a2", "a1"))
77+
f2 <- factor(c("b4", "b3", "b2", "b1"))
78+
79+
fcross <- fct_cross(f1, f2)
80+
81+
expect_equal(levels(fcross), c("a4:b4", "a3:b3", "a2:b2", "a1:b1"))
82+
})
83+
84+
85+
test_that("Cross factoring 3 levels in order by first level", {
86+
f1 <- fct_inorder(c("a4", "a3", "a2", "a1"))
87+
f2 <- factor(c("b4", "b3", "b2", "b1"))
88+
f3 <- factor(c("c4", "c3", "c2", "c1"))
89+
90+
fcross <- fct_cross(f1, f2, f3)
91+
92+
expect_equal(levels(fcross), c("a4:b4:c4", "a3:b3:c3", "a2:b2:c2", "a1:b1:c1"))
93+
})

0 commit comments

Comments
 (0)