diff --git a/NEWS.md b/NEWS.md index 4e4871310..e80cb30e0 100644 --- a/NEWS.md +++ b/NEWS.md @@ -2,6 +2,8 @@ * Bug fix in `add_ci.tbl_svysummary()` for factor variables where order was alphabetical instead of the factor levels. (#2036) +* Addressing encoding issue where `sort()` and `dplyr::arrange()` sorted differently, and the order of the `by` levels was inconsistent in the resulting table. (#2038) + # gtsummary 2.0.3 ### New Features and Functions diff --git a/R/tbl_summary.R b/R/tbl_summary.R index 857b4f465..971cc6c6b 100644 --- a/R/tbl_summary.R +++ b/R/tbl_summary.R @@ -452,8 +452,8 @@ tbl_summary <- function(data, !cards$context %in% "attributes", ) |> dplyr::select(cards::all_ard_groups(), "variable", "context") |> - dplyr::distinct() |> - dplyr::arrange(unlist(!!sym("group1_level"))) |> + dplyr::distinct() %>% + {.[order(unlist(.$group1_level)), ]} |> # styler: off dplyr::mutate( .by = cards::all_ard_groups(), gts_column = paste0("stat_", dplyr::cur_group_id()) diff --git a/tests/testthat/test-tbl_summary.R b/tests/testthat/test-tbl_summary.R index 99dab3a48..3a931073e 100644 --- a/tests/testthat/test-tbl_summary.R +++ b/tests/testthat/test-tbl_summary.R @@ -666,3 +666,18 @@ test_that("tbl_summary() data frame column labels are not dropped", { "Age" ) }) + +# addressing issue #2038 +test_that("tbl_summary() test encoding/sorting difference between sort() and dplyr::arrange()", { + # before this fix, the columns would print in reverse order, e.g. stat_3, stat_2, stat_1 + expect_equal( + data.frame( + groupe_etude = c(rep("Tem", 13), rep("TTA-", 7), rep("TTA+", 18)), + tympan_g_inc = rep(1,38) + ) |> + tbl_summary(by = groupe_etude, include = tympan_g_inc) |> + as.data.frame(col_labels = FALSE) |> + names(), + c("label", "stat_1", "stat_2", "stat_3") + ) +})