如何使用R语言tables包输出t.test的statistic和p.value结果
解决方案
不用提前通过lapply计算所有t检验结果,直接在tables::tabular()中自定义统计函数,即可直接提取t值和p值生成表格,步骤如下:
步骤1:预处理数据
首先过滤掉分组变量youngTreatment为缺失值的观测,避免t检验报错,同时加载所需包:
library(tables) # 过滤缺失分组的行 df_clean <- na.omit(candidateEvokeDFYoung)
步骤2:自定义t检验统计量提取函数
写一个简单的自定义函数,输入单个特征变量,自动按youngTreatment分组做t检验,返回需要的t统计量和p值:
t_test_stats <- function(var) { res <- t.test(var ~ df_clean$youngTreatment) c(`t统计量` = res$statistic, `p值` = res$p.value) }
步骤3:调用tabular生成表格
在tabular的公式中指定行是所有待检验的特征变量,列是我们自定义的统计函数即可:
# 仅输出t统计量和p值的表格 tabular( (candTrustworthy + candKnowledgeable + candQualified + candConservative + candLiberal + candInexperienced + candPrincipled + candDistance + candEfficacy) ~ t_test_stats, data = df_clean )
如果需要同时展示两组的均值,可以调整公式如下:
# 同时输出两组均值、t统计量、p值的表格 tabular( (candTrustworthy + candKnowledgeable + candQualified + candConservative + candLiberal + candInexperienced + candPrincipled + candDistance + candEfficacy) ~ (factor(youngTreatment, levels = c(0,1), labels = c("控制组", "处理组")))*mean + t_test_stats, data = df_clean )
如果你需要保留提前计算好的candidateEvokesDiffYoung列表来生成表格,只需要将列表转换为数据框后直接传入tabular即可,无需额外手动逐个提取字段:
# 从已有的t检验列表转换为数据框 ttest_df <- data.frame( 变量名 = names(candidateEvokesDiffYoung), t统计量 = sapply(candidateEvokesDiffYoung, \(x) x$statistic), p值 = sapply(candidateEvokesDiffYoung, \(x) x$p.value) ) # 直接生成表格 tabular(变量名 ~ t统计量 + p值, data = ttest_df)
内容的提问来源于stack exchange,提问作者Damon C. Roberts
相关产品推荐
相关产品推荐

