How Can I Add a Confidence Interval in tbl_summary?

The journal I am submitting to wants confidence intervals for categorical data. In tbl_summary, they just report the n/N and percentage. I tried to add a confidence interval to that by doing the following:

tbl_summary(statistic = list(all_continuous() ~ "{median} ({p25}, {p75})",
all_categorical() ~ "{n} / {N} ({p}%), ({conf.level*100}% CI {conf.low}, {conf.high})")) %>%

I watched the video on gtsummary and apparently you can add statistics, but I couldn't find where to get the code for a confidence interval.

I guess I was hoping I could just write in {ci}.

1 Like

Hi @drchinn!

There is no straight-forward way to do this. I did write something for you, however. I hope it helps.

library(gtsummary)
library(tidyverse)

tbl <-
  trial %>%
  select(grade, response) %>%
  tbl_summary(missing = "no") %>%
  add_n() %>%
  modify_footnote(everything() ~ NA)

# calculate CI and put it in format that can merge with tbl$table_body
tbl_ci <-
  tbl$meta_data %>%
  filter(summary_type %in% c("categorical", "dichotomous")) %>%
  select(summary_type, var_label, df_stats) %>%
  unnest(df_stats) %>%
  mutate(
    conf.low = (p - qnorm(0.975) * sqrt(p * (1 - p) / N)) %>% style_percent(symbol = TRUE),
    conf.high =( p + qnorm(0.975) * sqrt(p * (1 - p) / N)) %>% style_percent(symbol = TRUE),
    ci = str_glue("{conf.low}, {conf.high}"),
    label = coalesce(variable_levels, var_label),
    row_type = ifelse(summary_type == "dichotomous", "label", "level")
  ) %>%
  select(variable, row_type, label, ci) 

# merge in CI and set column header
tbl %>%
  modify_table_body(
    left_join,
    tbl_ci,
    by = c("variable", "row_type", "label")
  ) %>%
  modify_table_header(
    ci, 
    hide = FALSE,
    label = "**95% CI**"
  )

2 Likes

@statistishdan Thank you so much! Just what I needed.

1 Like

Great!

FYI, I don't often check the RStudio Community for gtsummary questions (I haven't figured out how to get an email when a question in posted!). If you post on stackoverflow.com and use the gtsummary tag, I think you'll find a more active community of folks responding to questions.

Happy Programming!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.