Home > front end >  How to add a column of statistics for only one group in gtsummary(tbl_summary)
How to add a column of statistics for only one group in gtsummary(tbl_summary)

Time:08-20

For example, now I have two groups of data, Drug A and Drug B. I would like to add a column of the number of observations of each variable for only Drug A, how can I do that? I don't find a way using add_n.

example table

The code for producing example table:

tbl_summary_ex2 <- trial %>% select(age, grade, response, trt) %>%
  tbl_summary(
    by = trt,
    label = list(age ~ "Patient Age"),
    statistic = list(all_continuous() ~ "{mean} ({sd})"),
    digits = list(age ~ c(0, 1))
  )

CodePudding user response:

Here is one way to do it:

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

# build table with only Drug A
tbl_summary_ex1 <- 
  trial %>% 
  dplyr::filter(trt == "Drug A") %>%
  select(age, grade, response) %>%
  tbl_summary(
    label = list(age ~ "Patient Age"),
    statistic = list(all_continuous() ~ "{mean} ({sd})"),
    digits = list(age ~ c(0, 1))
  ) %>%
  add_n(col_label = "**Drug A N**") %>%
  modify_column_hide(all_stat_cols())

# build table split by treatment
tbl_summary_ex2 <- 
  trial %>% 
  select(age, grade, response, trt) %>%
  tbl_summary(
    by = trt,
    label = list(age ~ "Patient Age"),
    statistic = list(all_continuous() ~ "{mean} ({sd})"),
    digits = list(age ~ c(0, 1))
  )

# merge tables together
tbl_final <-
  list(tbl_summary_ex1, tbl_summary_ex2) %>%
  tbl_merge(tab_spanner = FALSE)

enter image description here Created on 2022-08-19 by the reprex package (v2.0.1)

  • Related