You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在gtsummary中为同类型变量设置不同统计检验及自动选检验

使用gtsummary为不同分类变量指定统计检验及自动选择方法

一、正确排除指定分类变量

你之前的代码里all_categorical(-c('b','c'))写法不符合gtsummary的选择器规则,正确的排除方式是用减法运算符把变量从分类变量集合中移除。另外你原代码里连续变量的统计格式字符串少了右括号,也需要补上。

修正后的可运行代码:

library(gtsummary)
library(dplyr)

set.seed(123)
mydata <- data.frame(a = sample(c("Yes", "No"), 100, replace = TRUE),
                     b = sample(c("Yes", "No"), 100, replace = TRUE),
                     c = sample(c("Yes", "No"), 100, replace = TRUE),
                     d = sample(c("Low", "Medium", "High"), 100, replace = TRUE),
                     e = sample(c("Group 1", "Group 2", "Group 3"), 100, replace = TRUE),
                     f = sample(c("Male", "Female"), 100, replace = TRUE),
                     g = rnorm(100),
                     h = rnorm(100))

mydata %>%  
  tbl_summary(     
    by = a,                                            
    statistic = list(
      all_continuous() ~ "{median} ({p25}-{p75})",
      all_categorical() ~ "{n} / {N} ({p}%)"
    )
  ) %>% 
  add_p(
    all_continuous() ~ "t.test",
    all_categorical() - c("b", "c") ~ "chisq.test",  # 正确排除b、c
    c("b", "c") ~ "fisher.test", 
    pvalue_fun = function(x) style_number(x, digits = 3)
  )

二、自动选择合适的分类变量检验方法

gtsummary的add_p()不会自动切换检验方法,得自己写个函数来判断卡方检验的适用条件(比如期望单元格频数是否达标),自动选择卡方或Fisher精确检验。

下面的函数会先检查列联表的期望频数:如果有单元格期望<1,或者超过20%的单元格期望<5,就用Fisher检验,否则用卡方检验:

# 自定义自动选择检验的函数
auto_cat_test <- function(data, variable, by, ...) {
  tab <- table(data[[variable]], data[[by]])
  chisq_res <- chisq.test(tab)
  expected <- chisq_res$expected
  
  # 判断是否需要切换到Fisher检验
  need_fisher <- any(expected < 1) || sum(expected < 5)/length(expected) > 0.2
  
  if (need_fisher) {
    fisher.test(tab, ...)
  } else {
    chisq_res
  }
}

# 应用自定义函数
mydata %>%  
  tbl_summary(     
    by = a,                                            
    statistic = list(
      all_continuous() ~ "{median} ({p25}-{p75})",
      all_categorical() ~ "{n} / {N} ({p}%)"
    )
  ) %>% 
  add_p(
    all_continuous() ~ "t.test",
    all_categorical() ~ auto_cat_test,  # 所有分类变量自动选检验
    pvalue_fun = function(x) style_number(x, digits = 3)
  )

如果需要混合手动指定和自动选择,比如让b、c固定用Fisher,其余自动选择,可以这么写:

add_p(
  all_continuous() ~ "t.test",
  c("b", "c") ~ "fisher.test",
  all_categorical() - c("b", "c") ~ auto_cat_test,
  pvalue_fun = function(x) style_number(x, digits = 3)
)

内容的提问来源于stack exchange,提问作者Dreambig123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 09:55:11