From 014f09907bfc1c9b2fa1837c647845d55f5daf0d Mon Sep 17 00:00:00 2001 From: AdamK-A <103337795+AdamK-A@users.noreply.github.com> Date: Tue, 10 Dec 2024 12:27:27 -0800 Subject: [PATCH] Fixed factor cross ordering --- DESCRIPTION | 2 +- R/cross.R | 3 ++- tests/testthat/test-cross.R | 20 ++++++++++++++++++++ 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index ce124d87..2a131a62 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -38,4 +38,4 @@ Config/testthat/edition: 3 Encoding: UTF-8 LazyData: true Roxygen: list(markdown = TRUE) -RoxygenNote: 7.2.3 +RoxygenNote: 7.3.2 diff --git a/R/cross.R b/R/cross.R index 6901aa10..f37761a8 100644 --- a/R/cross.R +++ b/R/cross.R @@ -32,7 +32,8 @@ fct_cross <- function(..., sep = ":", keep_empty = FALSE) { newf <- exec(paste, !!!.data, sep = sep) old_levels <- lapply(.data, levels) - grid <- exec(expand.grid, old_levels) + grid_unsorted <- exec(expand.grid, old_levels) + grid <- grid_unsorted[do.call(order, grid_unsorted), ] new_levels <- exec(paste, !!!grid, sep = sep) if (!keep_empty) { diff --git a/tests/testthat/test-cross.R b/tests/testthat/test-cross.R index 3f6d827e..2d354fe3 100644 --- a/tests/testthat/test-cross.R +++ b/tests/testthat/test-cross.R @@ -71,3 +71,23 @@ test_that("validates its inputs", { fct_cross("x", keep_empty = 1) }) }) + +test_that("Cross factoring 2 levels in order", { + f1 <- fct_inorder(c("a4", "a3", "a2", "a1")) + f2 <- factor(c("b4", "b3", "b2", "b1")) + + fcross <- fct_cross(f1, f2) + + expect_equal(levels(fcross), c("a4:b4", "a3:b3", "a2:b2", "a1:b1")) +}) + + +test_that("Cross factoring 3 levels in order by first level", { + f1 <- fct_inorder(c("a4", "a3", "a2", "a1")) + f2 <- factor(c("b4", "b3", "b2", "b1")) + f3 <- factor(c("c4", "c3", "c2", "c1")) + + fcross <- fct_cross(f1, f2, f3) + + expect_equal(levels(fcross), c("a4:b4:c4", "a3:b3:c3", "a2:b2:c2", "a1:b1:c1")) +})