在tbl_stack的标头中列出总数N

时间:2020-10-26 08:00:11

标签: r gtsummary

当我执行tbl_stack时,我想在标题的tbl_stack中显示组合表的总数N。目前,结果似乎显示堆栈中第一个表的N。

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

tbl_stack(tbls=list(tbl_summary_ex2, tbl_summary_ex2a))

enter image description here 谢谢你的提示 杰夫

1 个答案:

答案 0 :(得分:0)

是的,正如tbl_stack()的文档所示,标头是从堆栈中的第一个gtsummary保留的。但是,您可以使用modify_header()函数来更改标题。另外,这些gtsummary表具有一个内部对象.$df_by,该对象保存每个表中的Ns。您可以使用这些内部数据帧对各个表的Ns求和。下面的示例以编程方式执行此操作,但是如果更容易,您可以简单地对Ns进行硬编码。

library(gtsummary)
library(tidyverse)

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

# calculate the sum total Ns from both tables
list_N <- 
  tbl_summary_ex2$df_by %>%
  bind_rows(tbl_summary_ex2a$df_by) %>%
  select(by_col, by, n) %>%
  group_by(by_col, by) %>%
  summarise(n = sum(n)) %>%
  mutate(
    header_update = 
      str_glue("{by_col} ~ '**{by}**, N = {n}'") %>%
      as.formula() %>%
      list()
  ) %>%
  pull(header_update)
list_N

tbl_stack(
  tbls=list(tbl_summary_ex2, tbl_summary_ex2a),
  group_header = c("Grade I", "Grade > I")
) %>%
  modify_header(list_N)

enter image description here