binyam girma
binyam girma

Reputation: 11

Using (gtsummary) tbl_svysummaary function to display confidence intervals for survey.design object?

I am using the tbl_svysummary() function for producing summary statistics tables from survey.design objects created by the {survey} package. The way one would go about it using the add_stat() function. However, I am facing an error when trying to use the add_stat() function.

ci <- function(vv1, vv2, dsgn) {
  svyby( as.formula( paste0( "~" , vv1)) , by = as.formula( paste0( "~" , vv2)), DHSdesign, svyciprop, vartype="ci")
}

tbl_svysummary_ex2 <-
  survey::svydesign(id= folate$EA_ID, strata=NULL,
                    weights = folate$weight,
                    data = folate) %>%
  tbl_svysummary(by = "folate_deficiency",
                 percent = "row", include = c(folate_deficiency,
                                              age_group,Region_Name, serum_folate,rbc_folate)) %>% 
 add_stat(
    fns = everything() ~ "Ci",
    location = "level",
    header = "**95% CI**"
  ) %>%
  modify_footnote(everything() ~ NA)

I am hoping if anyone can help me.

Upvotes: 1

Views: 684

Answers (1)

Daniel D. Sjoberg
Daniel D. Sjoberg

Reputation: 11680

An example table of what you're looking for along with code that I can run on my machine would have been helpful to get you exactly what you're looking for. I've created a reproducible example below that I think gets you at least close to what you're looking for?

library(gtsummary)
library(survey)

svy_trial <-
  svydesign(~1, data = trial %>% select(trt, response, death), weights = ~1) 

ci <- function(variable, by, data, ...) {
  svyby(as.formula( paste0( "~" , variable)) , by = as.formula( paste0( "~" , by)), data, svyciprop, vartype="ci") %>%
    tibble::as_tibble() %>%
    dplyr::mutate_at(vars(ci_l, ci_u), ~style_number(., scale = 100) %>% paste0("%")) %>%
    dplyr::mutate(ci = stringr::str_glue("{ci_l}, {ci_u}")) %>%
    dplyr::select(all_of(c(by, "ci"))) %>%
    tidyr::pivot_wider(names_from = all_of(by), values_from = ci) %>%
    set_names(paste0("add_stat_", seq_len(ncol(.))))
}

ci("response", "trt", svy_trial)
#> # A tibble: 1 x 2
#>   add_stat_1 add_stat_2
#>   <glue>     <glue>    
#> 1 21%, 40%   25%, 44%  

svy_trial %>%
  tbl_svysummary(by = "trt", missing = "no") %>%
  add_stat(everything() ~ "ci") %>%
  modify_table_body(
    dplyr::relocate, add_stat_1, .after = stat_1
  ) %>%
  modify_header(starts_with("add_stat_") ~ "**95% CI**") %>%
  modify_footnote(everything() ~ NA)

enter image description here

Upvotes: 1

Related Questions