如何为gtsummary的add_p()添加chisq.test的simulate.p.value参数?
解决方案
要在add_p()中给卡方检验添加simulate.p.value = TRUE参数,你需要自定义一个卡方检验函数,再在add_p()中指定使用这个自定义函数,具体步骤如下:
1. 自定义带模拟p值的卡方检验函数
先封装一个包含模拟参数的卡方检验函数,适配gtsummary的输出格式:
# 自定义卡方检验函数,开启模拟p值计算 chisq_test_sim <- function(data, variable, by, ...) { # 生成列联表 contingency_tbl <- table(data[[variable]], data[[by]]) # 调用chisq.test并开启模拟p值,默认模拟2000次(可调整B参数) test_result <- chisq.test(contingency_tbl, simulate.p.value = TRUE, B = 2000, ...) # 按gtsummary要求的格式返回结果 tibble::tibble( statistic = test_result$statistic, p.value = test_result$p.value, method = "Pearson's Chi-squared test with simulated p-value (based on 2000 replicates)" ) }
2. 在add_p()中调用自定义函数
修改现有代码,将test参数指定为自定义函数:
gtobject %>% gtsummary::add_p( test = c(var1, var2) ~ chisq_test_sim # 替换为你需要检验的变量名 )
补充说明
- 函数中
B = 2000是模拟重复次数,可根据需求调整(数值越大精度越高,但计算时间会增加)。 - 若不同变量需要不同检验方法,可在
test参数中分别指定,比如var1 ~ chisq_test_sim, var2 ~ t.test。
内容的提问来源于stack exchange,提问作者Mathica
相关产品推荐
相关产品推荐

