enter image description hereI have tried adding the confidence intervals in gtsummry but I get an error #>Error: Dimension of 'a1' and the added statistic do not match. Expecting statistic to be length 2. I successfully managed to add the intervals when I don't stratified by any variable. The code is as below-sorry if its too verbose.
#---- Libraries
library(gtsummary)
library(tidyverse)
#---- Data
set.seed(2021)
df <- tibble(
a1 = factor(ifelse(sign(rnorm(30))==-1, 0, 1), labels = c("No", "Yes")),
a2 = factor(ifelse(sign(rnorm(30))==-1, 0, 1), labels = c("No", "Yes")),
gender = gl(2, 15, labels = c("Males", "Females")),
b2 = gl(3, 10, labels = c("Primary", "Secondary", "Tertiary")),
c1 = gl(3, 10, labels = c("15-19", "20-24", "25-30")),
outcome = factor(ifelse(sign(rnorm(30))==-1, 0, 1), labels = c("No", "Yes")),
weight = runif(30, 1, 12)
)
#---- Function to calculate CIs
categorical_ci <- function(variable, tbl, ...) {
filter(tbl$meta_data, variable == .env$variable) %>%
pluck("df_stats", 1) %>%
mutate(
# calculate and format 95% CI
prop_ci = map2(n, N, ~prop.test(.x, .y)$conf.int %>%
style_percent(symbol = TRUE)),
ci = map_chr(prop_ci, ~glue::glue("{.x[1]}, {.x[2]}"))
) %>%
pull(ci)
}
#---- tblsummary with stratified by gender
t1 <- df %>%
select(gender, a1, a2) %>%
tbl_summary(by = gender, statistic = everything() ~ "{n} {p}%",
type = everything() ~ "categorical")
t1 %>%
add_stat(
fns = everything() ~ "categorical_ci",
location = "level",
header = "**95% CI**"
) %>%
modify_footnote(everything() ~ NA)