首页 > 解决方案 > 如何在 R 中进行 lm() 输出 welch t 测试

问题描述

我被告知并看到了线性模型和 t 检验基本上是相同的检验的示例,只是 t 检验是具有虚拟编码预测变量的专用线性模型。有没有办法让输出与 r 中lm的正常函数输出相同的 t 值、p 值、置信区间和标准误差,其中参数t.test的默认值为?var.equalFALSE

例如,现在 lm 和 t.test 的输出现在不同

data("mtcars")
#these outputs below give me different values 
summary(lm(mpg ~ am, mtcars))
t.test(mpg ~ am, mtcars)

我想要的是lm与 t.test 函数具有相同的值,这是一个 Welch t 检验。我该怎么做?

标签: r

解决方案


首先,在 CrossValidated 上有一篇很棒的文章,回归、t 检验和 ANOVA 所有版本的一般线性模型如何? 这提供了很多关于t检验、线性回归和 ANOVA之间关系的背景信息。

本质上,来自 t检验的 p 值对应于线性模型中斜率参数的 p 值。

在您的情况下,您需要比较

t.test(mpg ~ am, mtcars, alternative = "two.sided", var.equal = T)
#
#   Two Sample t-test
#
#data:  mpg by am
#t = -4.1061, df = 30, p-value = 0.000285
#alternative hypothesis: true difference in means is not equal to 0
#95 percent confidence interval:
# -10.84837  -3.64151
#sample estimates:
#mean in group 0 mean in group 1
#       17.14737        24.39231

fit <- lm(mpg ~ as.factor(am), mtcars)
summary(fit)
#
#Call:
#lm(formula = mpg ~ as.factor(am), data = mtcars)
#
#Residuals:
#    Min      1Q  Median      3Q     Max
#-9.3923 -3.0923 -0.2974  3.2439  9.5077
#
#Coefficients:
#               Estimate Std. Error t value Pr(>|t|)
#(Intercept)      17.147      1.125  15.247 1.13e-15 ***
#as.factor(am)1    7.245      1.764   4.106 0.000285 ***
#---
#Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
#
#Residual standard error: 4.902 on 30 degrees of freedom
#Multiple R-squared:  0.3598,   Adjusted R-squared:  0.3385
#F-statistic: 16.86 on 1 and 30 DF,  p-value: 0.000285

请注意,p 值一致。

两条评论:

  1. as.factor(am)变成am分类变量
  2. 为了匹配线性模型的假设(其中误差项epsilon ~ N(0, sigma^2)),我们需要使用t.testwhichvar.equal = T假设两组测量的方差相同。
  3. t值符号的不同来自于对“分类”的参考水平的不同定义am

为了在线性模型中获得相同的组均值,我们可以去掉截距

lm(mpg ~ as.factor(am) - 1, mtcars)
#
#Call:
#lm(formula = mpg ~ as.factor(am) - 1, data = mtcars)
#
#Coefficients:
#as.factor(am)0  as.factor(am)1
#         17.15           24.39

推荐阅读