R语言使用combn()做t-test时如何匹配对应的对比变量?
R 两两t检验配对对应问题解决方案
原代码参数错误说明
你当前combn()的m参数设置错误:m=1代表每次仅从数据集中抽取1列执行t检验,属于单样本t检验逻辑,不符合你两两变量交叉校验的需求。两两检验需要设置m=2,代表每次抽取2列执行检验。
带配对标识的实现代码
你可以直接使用下方代码生成带变量对应关系的检验结果表,不需要手动匹配p值位置:
# 方式1:base R 原生实现,无需额外依赖 # 生成所有两变量组合 var_combinations <- combn(colnames(trust_news), m = 2, simplify = FALSE) # 遍历组合执行t检验,组装结果 t_test_res <- do.call(rbind, lapply(var_combinations, function(pair) { test_res <- t.test(trust_news[[pair[1]]], trust_news[[pair[2]]]) data.frame( variable_1 = pair[1], variable_2 = pair[2], p_value = test_res$p.value, t_value = test_res$statistic ) })) # 方式2:如果你习惯tidyverse风格,可使用下方代码 library(tidyverse) t_test_res <- combn(colnames(trust_news), m = 2, simplify = FALSE) %>% map_dfr(~{ test_res <- t.test(trust_news[[.x[1]]], trust_news[[.x[2]]]) tibble(variable_1 = .x[1], variable_2 = .x[2], p_value = test_res$p.value) })
额外说明
- 如果你需要执行配对t检验、设置方差齐性等参数,直接在
t.test()函数内补充paired = TRUE、var.equal = TRUE等参数即可 - 如果需要做多重检验校正,可直接对结果表的p值列调用
p.adjust()函数处理,例如:t_test_res$adjusted_p <- p.adjust(t_test_res$p_value, method = "fdr")
内容的提问来源于stack exchange,提问作者cigarette_daygreams
相关产品推荐
相关产品推荐

