Is there currently a way in gtsummary to create columns for the p values of each pairwise comparison for a post hoc test? For example, say there are 4 groups, is there a function that includes the p values as separate columns for
You can use the add_stat()
function to add custom columns and rows to a tbl_summary()
table. The example below uses the pairwise.t.test()
to calculate the pairwise p-values (you can use whatever method you like).
library(gtsummary)
packageVersion("gtsummary")
#> [1] '1.5.0'
# set theme to get MEAN (SD) by default in `tbl_summary()`
theme_gtsummary_mean_sd()
# function to add pairwise copmarisons to `tbl_summary()`
add_stat_pairwise <- function(data, variable, by, ...) {
# calculate pairwise p-values
pw <- pairwise.t.test(data[[variable]], data[[by]], p.adj = "none")
# convert p-values to list
index <- 0L
p.value.list <- list()
for (i in seq_len(nrow(pw$p.value))) {
for (j in seq_len(nrow(pw$p.value))) {
index <- index + 1L
p.value.list[[index]] <-
c(pw$p.value[i, j]) %>%
setNames(glue::glue("**{colnames(pw$p.value)[j]} vs. {rownames(pw$p.value)[i]}**"))
}
}
# convert list to data frame
p.value.list %>%
unlist() %>%
purrr::discard(is.na) %>%
t() %>%
as.data.frame() %>%
# formatting/roundign p-values
dplyr::mutate(dplyr::across(everything(), style_pvalue))
}
trial %>%
select(grade, age, marker) %>%
tbl_summary(by = grade, missing = "no") %>%
# add pariwaise p-values
add_stat(everything() ~ add_stat_pairwise) %>%
as_kable() # convert to kable to display on Stackoverflow
Characteristic | I, N = 68 | II, N = 68 | III, N = 64 | I vs. II | I vs. III | II vs. III |
---|---|---|---|---|---|---|
Age | 46 (15) | 48 (14) | 48 (14) | 0.6 | 0.4 | 0.8 |
Marker Level (ng/mL) | 1.07 (0.89) | 0.68 (0.73) | 1.00 (0.92) | 0.010 | 0.6 | 0.040 |
Created on 2021-11-26 by the reprex package (v2.0.1)