r - 如何在 R 中进行 lm() 输出 welch t 测试

标签 r

有人告诉我,也见过一些例子,其中线性模型和 t 检验基本上是相同的检验,只是 t 检验是带有虚拟编码预测变量的专门线性模型。有没有办法让 lm 的输出输出与 r 中正常 t.test 函数相同的 t 值、p 值、置信区间和标准误差,其中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 上有一篇很棒的文章 How are regression, the t-test, and the ANOVA all versions of the general linear model? 它提供了有关 t 检验、线性回归和方差分析之间关系的大量背景信息。

本质上,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.testvar.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

关于r - 如何在 R 中进行 lm() 输出 welch t 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55369798/

相关文章:

r - 在绘图框中使用相同的坐标和相同的位置绘制两个 igraph 网络

r - 给列表赋值时出错

r - 如何在RStudio绘图设备中删除当前(但不是全部)绘图?

r - 在 R 中使用格式时如何保留 NA?

r - 尝试使用 R 中的 RWeka 包应用决策 C4.5 算法时出错

r - 如何使用 R 中的 caret 包训练具有偏移项的 glmnet 模型(泊松族)?

r - R 中的 for 循环在多个文件上运行函数,计算输出值,放入新文件中

r - 在 R 中使用 optim() 或 optimize() 函数

r - 让 R 等待控制台输入?

r - 使用性别_df 和性别函数时出错