diff --git a/NEWS.md b/NEWS.md index 345d1dfa4..4e4871310 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,7 @@ # gtsummary (development version) +* Bug fix in `add_ci.tbl_svysummary()` for factor variables where order was alphabetical instead of the factor levels. (#2036) + # gtsummary 2.0.3 ### New Features and Functions diff --git a/R/add_ci.R b/R/add_ci.R index 32831da7b..0af17c2b2 100644 --- a/R/add_ci.R +++ b/R/add_ci.R @@ -219,7 +219,16 @@ brdg_add_ci <- function(x, pattern, statistic, include, conf.level, updated_call .y } ) |> - dplyr::bind_rows() + dplyr::bind_rows() %>% + # ensuring it appears in the original order (issue with survey data GH #2036) + dplyr::left_join( + x = x$cards$add_ci |> + dplyr::distinct(dplyr::pick(cards::all_ard_groups(), cards::all_ard_variables())), + y = ., + by = x$cards$add_ci |> + dplyr::select(cards::all_ard_groups(), cards::all_ard_variables()) |> + names() + ) # format results to merge into primary table --------------------------------- df_prepped_for_merge <- diff --git a/tests/testthat/test-add_ci.tbl_svysummary.R b/tests/testthat/test-add_ci.tbl_svysummary.R index 37082c57f..bcc566aa1 100644 --- a/tests/testthat/test-add_ci.tbl_svysummary.R +++ b/tests/testthat/test-add_ci.tbl_svysummary.R @@ -1,5 +1,5 @@ skip_on_cran() -skip_if_not(is_pkg_installed(c("cardx", "survey"), reference_pkg = "gtsummary") && is_pkg_installed("broom", reference_pkg = "cardx")) +skip_if_not(is_pkg_installed(c("cardx", "survey", "withr"), reference_pkg = "gtsummary") && is_pkg_installed("broom", reference_pkg = "cardx")) svy_trial <- survey::svydesign(~1, data = trial, weights = ~1) test_that("add_ci(method) with no `by`", { @@ -740,3 +740,36 @@ test_that("add_ci() messaging for tbl_svysummary(percent)", { "function is meant to work with" ) }) + +test_that("add_ci.tbl_svysummary() ordering for factors", { + withr::local_seed(123) + + # generate sample data + expect_error( + df <- + dplyr::tibble(factor = sample(c("A", "B", "C", NA), 100, replace = TRUE)) |> + dplyr::mutate( + factor2 = factor(factor, levels = c("C", "B", "A")), + factor = factor(factor), + ) |> + survey::svydesign(ids = ~ 1, data = _, weights = ~1) |> + tbl_svysummary(missing = "no") |> + add_ci() |> + modify_column_unhide(variable) |> + remove_row_type() |> + as.data.frame(col_label = FALSE), + NA + ) + + expect_equal( + df |> + dplyr::filter(variable == "factor") |> + dplyr::arrange(label) |> + dplyr::select(label, stat_0, ci_stat_0), + df |> + dplyr::filter(variable == "factor2") |> + dplyr::arrange(label) |> + dplyr::select(label, stat_0, ci_stat_0) + ) +}) +