gtsummary: Is it possible to add 'n' for each column of table when the tbl_summary is stratified by two groups

28 views Asked by At

I am utilizing gtsummary::tbl_summary to generate a data table. I am employing the following code to stratify it into two groups. My code gives "n" for the main category only. But I want to include "n" counts for each of the columns/groups, as illustrated in the attached figure. Can someone please help me

 mtcars %>%
    select(am, cyl, mpg, hp) %>%
    dplyr::mutate(
        cyl = paste(cyl, "Cylinder"),
        am = factor(am, labels = c("Automatic", "Manual"))
    ) %>%
    tbl_strata(
        strata = cyl,
        ~.x %>%
            tbl_summary(
                by = am,
                type = where(is.numeric) ~ "continuous"
            ) %>% add_n() %>%
            modify_header(all_stat_cols() ~ "**{level}**")
    )

enter image description here

1

There are 1 answers

0
Daniel D. Sjoberg On BEST ANSWER

You can dynamically add the column Ns using modify_header(). Example below!

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

tbl <- mtcars %>%
  select(am, cyl, mpg, hp) %>%
  dplyr::mutate(
    cyl = paste(cyl, "Cylinder"),
    am = factor(am, labels = c("Automatic", "Manual"))
  ) %>%
  tbl_strata(
    strata = cyl,
    ~.x %>%
      tbl_summary(
        by = am,
        type = where(is.numeric) ~ "continuous"
      ) %>%
      modify_header(all_stat_cols() ~ "**{level}**  \nN = {n}")
  )

enter image description here Created on 2024-03-14 with reprex v2.1.0