Skip to content

Commit b9049f7

Browse files
authored
In fct_cross() vary last factor levels fastest, not first (#373)
Fixes #360
1 parent e2b3923 commit b9049f7

File tree

3 files changed

+12
-2
lines changed

3 files changed

+12
-2
lines changed

NEWS.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# forcats (development version)
22

3+
* `fct_cross()` now varies the levels in the last factor fastest (@Adam-AKong, #373).
34
* Functions that create a new factor (e.g. `lvls_expand()`, `lvls_reorder()`, `fct_lump_n()`, `fct_drop()`) now preserves the class of the original object in addition to the attributes (#83).
45
* forcats now requires R 4.1.
56

R/cross.R

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,9 @@ 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)
36-
new_levels <- exec(paste, !!!grid, sep = sep)
35+
# expand.grid varies inputs fastest instead of last
36+
grid_rev <- exec(expand.grid, rev(old_levels))
37+
new_levels <- exec(paste, !!!rev(grid_rev), sep = sep)
3738

3839
if (!keep_empty) {
3940
new_levels <- intersect(new_levels, newf)

tests/testthat/test-cross.R

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,3 +81,11 @@ test_that("validates its inputs", {
8181
fct_cross("x", keep_empty = 1)
8282
})
8383
})
84+
85+
test_that("varies last values fastest", {
86+
f1 <- fct(c("a4", "a3", "a2", "a1"))
87+
f2 <- fct(c("b4", "b3", "b2", "b1"), levels = c("b4", "b3", "b2", "b1"))
88+
89+
fcross <- fct_cross(f1, f2)
90+
expect_equal(levels(fcross), c("a4:b4", "a3:b3", "a2:b2", "a1:b1"))
91+
})

0 commit comments

Comments
 (0)