Skip to content

Commit

Permalink
fixing ordering bug (#2037)
Browse files Browse the repository at this point in the history
  • Loading branch information
ddsjoberg authored Oct 9, 2024
1 parent b183b75 commit af17cb2
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 2 deletions.
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
11 changes: 10 additions & 1 deletion R/add_ci.R
Original file line number Diff line number Diff line change
Expand Up @@ -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 <-
Expand Down
35 changes: 34 additions & 1 deletion tests/testthat/test-add_ci.tbl_svysummary.R
Original file line number Diff line number Diff line change
@@ -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`", {
Expand Down Expand Up @@ -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)
)
})

0 comments on commit af17cb2

Please sign in to comment.