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()