【发布时间】:2020-02-24 14:18:15
【问题描述】:
我无法理解 glm 的效果编码。举个例子:
data('mpg')
mpg$trans = as.factor(mpg$trans)
levels(mpg$trans)
[1] "auto(av)" "auto(l3)" "auto(l4)" "auto(l5)" "auto(l6)" "auto(s4)" "auto(s5)" "auto(s6)" "manual(m5)" "manual(m6)"
对于效果(或虚拟)编码,glm 将第一级作为参考级,因此在这种情况下它将是“auto(av)”。
mpg_glm = glm(hwy ~ trans, data = mpg, contrasts = list(trans = contr.sum))
summary(mpg_glm)
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 24.4173 0.7318 33.366 < 2e-16 ***
trans1 3.3827 2.3592 1.434 0.153017
trans2 2.5827 3.6210 0.713 0.476426
trans3 -2.4534 0.9157 -2.679 0.007928 **
trans4 -3.6993 1.0865 -3.405 0.000784 ***
trans5 -4.4173 2.1743 -2.032 0.043375 *
trans6 1.2494 2.9866 0.418 0.676105
trans7 0.9160 2.9866 0.307 0.759341
trans8 0.7702 1.4517 0.531 0.596262
trans9 1.8758 0.9845 1.905 0.058011 .
所以我现在认为 trans1 实际上是 第二 级别(“auto(l3)”),因为第一个是参考级别。为了测试这一点,我重新调整了因子,以便看到第一级的系数(“auto(av)”):
mpg$trans <- relevel(mpg$trans, ref="auto(l3)")
levels(mpg$trans)
"auto(l3)" "auto(av)" "auto(l4)" "auto(l5)" "auto(l6)" "auto(s4)" "auto(s5)" "auto(s6)" "manual(m5)" "manual(m6)"
现在我期待看到第一级的系数和第二级的系数不见了(因为现在是参考水平):
mpg_glm = glm(hwy ~ trans, data = mpg, contrasts = list(trans = contr.sum))
summary(mpg_glm)
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 24.4173 0.7318 33.366 < 2e-16 ***
trans1 2.5827 3.6210 0.713 0.476426
trans2 3.3827 2.3592 1.434 0.153017
trans3 -2.4534 0.9157 -2.679 0.007928 **
trans4 -3.6993 1.0865 -3.405 0.000784 ***
trans5 -4.4173 2.1743 -2.032 0.043375 *
trans6 1.2494 2.9866 0.418 0.676105
trans7 0.9160 2.9866 0.307 0.759341
trans8 0.7702 1.4517 0.531 0.596262
trans9 1.8758 0.9845 1.905 0.058011 .
我看到唯一改变的是前2个系数被切换了,那么以哪个级别作为参考?我在这里错过了什么?
【问题讨论】:
标签: r glm dummy-variable coefficients