'Split categorical post hoc tests error gtsummary plus add_by_n
I want to make a table with 3 different groups. I need to get the n of each treatment groups variables. Then I want a post hoc test of the multigroup comparisons.
This one made by package author on stackoverflow works with same format I want here for t tests only so I tried to adapt it to categorical below following instructions, but had errors
Original working version here
# 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))
}
Updated version for categorical variables
require(rstatix)
require(dplyr)
add_stat_cat <- function(data, variable, by, ...) {
# calculate pairwise p-values
fish_df <- pairwise_fisher_test(table(data[[variable]], data[[by]], p.adj = "none"))
#make into dataframe
df_ps_fish<-data.frame(fish_df$p.adj, paste0(fish_df$group1," vs. " ,fish_df$group2))
df_ps_fish %>% pivot_wider(values_from = fish_df.p.adj, names_from = paste0.fish_df.group1....vs....fish_df.group2.)}
which I then try to implement with this to see if it works for the death variable, and ignores marker variable.
trial %>%
select(grade, death, marker) %>%
tbl_summary(by = grade, missing = "no") %>%
# add pariwaise p-values
add_stat(everything() ~ add_stat_cat)
I receive this error
There was an error for variable 'death': Error in table(data[[variable]], data[[by]], p.adj = "none"): all arguments must have the same length
I want to later add if statements such that the function switches between categorical and continuous based on variable’s class, and then combine with other stat columns but I need to get these pieces before that. I don’t think I can ask multiple questions in one post though
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
