gtsummary 制表

library(gtsummary)

library(knitr)

theme_gtsummary_language("en", big.mark = "")

options(knitr.kable.NA = '')

library(flextable)

library(officer) 


#分类变量显示百分比,2位小数

set_gtsummary_theme(list(

  `tbl_summary-fn:percent_fun` = function(x) sprintf("%.2f", x * 100)

))


theme_gtsummary_journal("lancet")


# 允许不同风格相互叠加

theme_gtsummary_compact()


my_test <- function(data, variable, by, ...) {

  if (is.numeric(data[[variable]])) {

    # For continuous variables, use oneway.test

    oneway.test(data[[variable]] ~ as.factor(data[[by]])) %>%

      broom::tidy() %>%

      select(statistic, p.value)

  } else {

    # For categorical variables, use chisq.test

    chisq.test(table(data[[variable]], data[[by]])) %>%

      broom::tidy() %>%

      select(statistic, p.value)

  }

}


my_table <- df %>%

  select(服药依从性, 年龄, 民族, 性别, 文化程度, 职业, 婚姻状况, 经济状况, 户别, 医疗费用支付方式, 家族史) %>%

  tbl_summary(by = 服药依从性, statistic = (

    list(

      all_continuous() ~ "{mean} (±{sd})",

      # 设置所有连续变量的描述方式

      all_categorical() ~ "{n} ({p}%)",

      # 设置所有分类变量的描述方式

      digits = list(all_continuous()  ~ c(2, 2), all_categorical() ~ c(0, 2))

    )

  ),

  # missing = "no", # 此行代码将不显示缺失值

  missing_text = "Missing", # 将缺失值一栏显示为"Missing"

  ) %>%

  # add_p(

  #   pvalue_fun = ~ style_pvalue(.x, digits = 3),

  #   list(all_continuous() ~ "oneway.test", #aov

  #        all_categorical() ~ "chisq.test")

  # ) %>%

  add_stat(fns = everything() ~ my_test) %>%

  modify_header(label ~ "**Variable**") %>%

  modify_fmt_fun(statistic ~ style_sigfig) %>% 

  modify_spanning_header(c("stat_1", "stat_2", "stat_3") ~ "**服药依从性**") %>%

  modify_caption("**Table 1. 患者特征**") %>%

  bold_labels() 

评论

此博客中的热门博文

V2ray websocket(ws)+tls+nginx分流

Rstudio 使用代理