Getting an extra column for median in gtsummary table

Viewed 111

I saw an article that I'd like to replicate. They had categorical predictions as the rows, and use N for column 1 and Median of another variable for column 2. I'd like to be able to create a function to get me Median for Column 2. Sample image enter image description here

I'm not sure how to get the median at each specific level. I tried group by, but that would only give me median's per higher level.

library(gtsummary)

trial2 <- trial %>% select(stage, grade, ttdeath) %>% 
  group_by(stage, grade) %>% 
  mutate(median_ttdeath = median(ttdeath))
1 Answers

The easiest way to report continuous summaries within a group, is to use the tbl_continuous() function. https://www.danieldsjoberg.com/gtsummary/reference/tbl_continuous.html

In your case, you'll need to make 2 summary tables, then merge the tables together. Example below!

library(gtsummary)
packageVersion("gtsummary")
#> [1] '1.5.0'

tbl1 <- 
  trial %>%
  select(trt, grade) %>%
  tbl_summary()

tbl2 <- 
  trial %>%
  tbl_continuous(
    variable = age,
    include = c(trt, grade)
  ) %>%
  modify_header(all_stat_cols() ~ "**Age**")

tbl_final <-
  tbl_merge(list(tbl1, tbl2)) %>%
  modify_spanning_header(everything() ~ NA)

enter image description here Created on 2021-11-15 by the reprex package (v2.0.1)

Related