Am trying to collapse to columns in order to have a single column so as to suit a given table structure. The desired output is to be for 23 (21.2 - 24.5). I have the two tables already created but I don't seem to get it. In essence I would like the proportions and CI to be in a single column with just one title % (95% CI)
library(gtsummary)
library(tidyverse)
# Obtain proportions
tbl1 <-
trial %>%
mutate(trt = as.factor(trt)) %>%
select(grade, response, trt) %>%
tbl_summary(missing = "no", type = everything() ~ "categorical",
statistic = all_categorical() ~ "{p}")
myci2 <-
tbl1$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 <-
tbl1 %>%
modify_table_body(
left_join,
myci2,
by = c("variable", "row_type", "label")
) %>%
modify_header(ci = "**% (95% CI)**")
finaltbl
finaltbl[["table_body"]] <- finaltbl[["table_body"]] %>%
mutate(prev = paste0(stat_0, " (", ci, ")"))
finaltbl %>%
modify_column_unhide(prev) %>%
modify_column_hide(c(stat_0, ci))
Example below!
library(gtsummary)
library(tidyverse)
#> Warning: package 'readr' was built under R version 4.1.1
packageVersion("gtsummary")
#> [1] '1.4.2.9008'
# Obtain proportions
tbl1 <-
trial %>%
mutate(trt = as.factor(trt)) %>%
select(grade, response, trt) %>%
tbl_summary(missing = "no", type = everything() ~ "categorical",
statistic = all_categorical() ~ "{p}%")
myci2 <-
tbl1$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("{style_percent(p)}% ({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 <-
tbl1 %>%
modify_table_body(
left_join,
myci2,
by = c("variable", "row_type", "label")
) %>%
modify_header(ci = "**% (95% CI)**") %>%
modify_column_hide(stat_0)
Created on 2021-09-18 by the reprex package (v2.0.1)