如何调整R中gtsummary表格的格式与统计输出?
gtsummary表格修改方案
完整修改代码
# 先统一示例数据列名与代码变量名匹配 pre_int <- pre_int %>% rename( Gender_Identity = `Gender Identity`, Interpreter_Used = `Interpreter Used` ) # 生成符合要求的统计表格 table1 <- tbl_summary( pre_int, include = c(Age, Gender_Identity), by = Interpreter_Used, # 年龄变量显示均值与标准差 statistic = list( Age ~ "{mean} ({sd})", all_categorical() ~ "{n} ({p}%)" ) ) %>% add_n() %>% modify_header(label = "**Variable**") %>% bold_labels() %>% # 百分比格式化为两位有效数字 modify_fmt_fun( update = all_stat_cols() ~ function(x) { stringr::str_replace_all(x, "\\((\\d+\\.?\\d*)%\\)", function(match) { num <- as.numeric(sub("%", "", match)) paste0("(", style_number(num, digits = 2), "%)") }) } ) %>% # 为分类变量子类别添加p值 add_p( test = list( Age ~ "t.test", Gender_Identity ~ "chisq.test" ), pvalue_fun = ~style_pvalue(.x, digits = 3), test.args = list(keep.test = TRUE) ) %>% # 将变量级p值复制到对应子类别行 modify_table_body( mutate, p.value = ifelse(row_type == "level", first(p.value[variable == .data$variable]), p.value) ) # 查看表格 table1
各需求对应修改说明
- 年龄显示均值与标准差:在
tbl_summary的statistic参数中,为Age变量指定统计量格式为"{mean} ({sd})",直接替换默认的中位数+四分位距输出。 - 百分比保留两位有效数字:通过
modify_fmt_fun结合正则表达式匹配表格中的百分比数值,用style_number将其格式化为两位有效数字后重新拼接,确保百分比显示符合要求。 - 分类变量子类别生成p值:先通过
add_p为变量指定合适的检验方法(年龄用t检验,性别用卡方检验),并保留检验结果;再用modify_table_body将主变量的p值复制到该变量的所有子类别行,实现每个子类别显示对应p值的效果。
内容的提问来源于stack exchange,提问作者cake2244
相关产品推荐
相关产品推荐

