Art*_*Sbr 4 statistics r linear-regression lm
我正在使用分类变量进行回归并遇到了这个问题。在这里,用户想要为每个虚拟对象添加一列。这让我很困惑,因为我虽然在列中包含所有存储的as.factor()虚拟变量的长数据相当于拥有虚拟变量。
有人可以解释以下两个线性回归模型之间的区别吗?
线性模型 1,其中月份是一个因素:
dt_long
Sales Period Month
1: 0.4898943 1 M1
2: 0.3097716 1 M1
3: 1.0574771 1 M1
4: 0.5121627 1 M1
5: 0.6650744 1 M1
---
8108: 0.5175480 24 M12
8109: 1.2867316 24 M12
8110: 0.6283875 24 M12
8111: 0.6287151 24 M12
8112: 0.4347708 24 M12
M1 <- lm(data = dt_long,
fomrula = Sales ~ Period + factor(Month)
Run Code Online (Sandbox Code Playgroud)
线性模型 2,其中每个月都是一个指标变量:
dt_wide
Sales Period M1 M2 M3 M4 M5 M6 M7 M8 M9 M10 M11 M12
1: 0.4898943 1 1 0 0 0 0 0 0 0 0 0 0 0
2: 0.3097716 1 1 0 0 0 0 0 0 0 0 0 0 0
3: 1.0574771 1 1 0 0 0 0 0 0 0 0 0 0 0
4: 0.5121627 1 1 0 0 0 0 0 0 0 0 0 0 0
5: 0.6650744 1 1 0 0 0 0 0 0 0 0 0 0 0
---
8108: 0.5175480 24 0 0 0 0 0 0 0 0 0 0 0 1
8109: 1.2867316 24 0 0 0 0 0 0 0 0 0 0 0 1
8110: 0.6283875 24 0 0 0 0 0 0 0 0 0 0 0 1
8111: 0.6287151 24 0 0 0 0 0 0 0 0 0 0 0 1
8112: 0.4347708 24 0 0 0 0 0 0 0 0 0 0 0 1
M2 <- lm(data = data_wide,
formula = Sales ~ Period + M1 + M2 + M3 + ... + M11 + M12
Run Code Online (Sandbox Code Playgroud)
从之前提出的这个问题来看,两种模型似乎完全相同。但是,在运行这两个模型后,我注意到M1返回 11 个虚拟估计量(因为 M1 用作参考水平),而 M2 返回 12 个虚拟估计量。
一种模型比另一种更好吗?M1效率更高?我可以在 M1 中设置参考电平以使两个模型完全相同吗?
定义模型M1只是包含虚拟变量的捷径:如果您想手动计算这些回归系数,显然它们必须是数字。
现在,您可能没有注意到M2其中一个假人应该具有 NA 系数。那是因为您手动包含了所有这些并离开了拦截。这样我们就有了一个完美的共线性问题。通过不包括其中一个假人或添加-1以消除常数项,一切都会好起来的。
一些例子。让
y <- rnorm(100)
x0 <- rep(1:0, each = 50)
x1 <- rep(0:1, each = 50)
x <- factor(x1)
Run Code Online (Sandbox Code Playgroud)
这样x0并且x1是 的分解x。然后
## Too much
lm(y ~ x0 + x1)
# Call:
# lm(formula = y ~ x0 + x1)
# Coefficients:
# (Intercept) x0 x1
# -0.15044 0.07561 NA
## One way to fix it
lm(y ~ x0 + x1 - 1)
# Call:
# lm(formula = y ~ x0 + x1 - 1)
# Coefficients:
# x0 x1
# -0.07483 -0.15044
## Another one
lm(y ~ x1)
# Call:
# lm(formula = y ~ x1)
# Coefficients:
# (Intercept) x1
# -0.07483 -0.07561
## The same results
lm(y ~ x)
# Call:
# lm(formula = y ~ x)
# Coefficients:
# (Intercept) x1
# -0.07483 -0.07561
Run Code Online (Sandbox Code Playgroud)
最终所有模型都包含相同数量的信息,但在多重共线性的情况下,我们面临识别问题。