I have successfully calculated confidence intervals in a table but unable to join the two tables to have one. It seem not to work. The desired output is to have the Interestingly there is no error.
library(gtsummary)
library(tidyverse)
tbl2 <-
trial %>%
mutate(trt = as.factor(trt)) %>%
select(grade, response, trt) %>%
tbl_summary(missing = "no", type = everything() ~ "categorical")
myci2 <- tbl2$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)
finaltbl <- tbl2 %>%
modify_table_body(
left_join,
myci2,
by = c("variable", "row_type", "label")
)
The issue is that the new column is, by default, hidden from the output. You can unhide a column by either assigning a header with modify_header()
or with modify_column_unhide()
.
library(gtsummary)
#> #BlackLivesMatter
library(tidyverse)
#> Warning: package 'readr' was built under R version 4.1.1
packageVersion("gtsummary")
#> [1] '1.4.2'
tbl2 <-
trial %>%
mutate(trt = as.factor(trt)) %>%
select(grade, response, trt) %>%
tbl_summary(missing = "no", type = everything() ~ "categorical")
myci2 <-
tbl2$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)
finaltbl <-
tbl2 %>%
modify_table_body(
left_join,
myci2,
by = c("variable", "row_type", "label")
) %>%
# adding a column header UNHIDES the column (you could also use `modify_column_unhide()`)
modify_header(ci = "**95% CI**")
Created on 2021-09-17 by the reprex package (v2.0.1)
FYI, in the next version of gtsummary, there is a function that will add the CI and you won't need to calculate it yourself: add_ci()
.