r - 如何在 R 中进行 lm() 输出 welch t 测试
问题描述
我被告知并看到了线性模型和 t 检验基本上是相同的检验的示例,只是 t 检验是具有虚拟编码预测变量的专用线性模型。有没有办法让输出与 r 中lm
的正常函数输出相同的 t 值、p 值、置信区间和标准误差,其中参数t.test
的默认值为?var.equal
FALSE
例如,现在 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 检验。我该怎么做?
解决方案
首先,在 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 值一致。
两条评论:
as.factor(am)
变成am
分类变量- 为了匹配线性模型的假设(其中误差项
epsilon ~ N(0, sigma^2)
),我们需要使用t.test
whichvar.equal = T
假设两组测量的方差相同。 - 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
推荐阅读
- android - 失去新活动的所有价值 - Kotlin
- debugging - 如何在打开 QuickView 窗口的同时浏览代码?
- php - 如何使用 XAMPP 打开 PHP 文件?
- javascript - 如何在 Chrome 中正确预取 json 端点?
- android - 如何在关注可重用性和关注点分离的 android 库模块之间实现导航?
- algorithm - 通过普通算法构建后缀树是否需要构建后缀树作为第一阶段?
- c# - 加载 DataGrid (MVVM) 时显示 WPF DataGridComboBoxColumn 的值
- bbedit - BBEdit 中的美人鱼和 MMD?
- unix - unix 中的命令/脚本在 ascci 中转换大型机 ebcdic 文件
- cakephp - html链接中的Cakephp跨度