为 R 中的分类变量设置不同级别的常量
Setting Different Levels of constants for categorical variables in R
谁能解释一下如何在 r 中为不同级别的分类变量设置常量?
我已阅读以下内容:How to set the Coefficient Value in Regression; R 它很好地解释了如何为整个分类变量设置常量。我想知道如何为每个级别设置一个。
例如,让我们看一下 MTCARS 数据集:
df <- as.data.frame(mtcars)
df$cyl <- as.factor(df$cyl)
set.seed(1)
glm(mpg ~ cyl + hp + gear, data = df)
这给了我以下输出:
Call: glm(formula = mpg ~ cyl + hp + gear, data = df)
Coefficients:
(Intercept) cyl6 cyl8 hp gear
19.80268 -4.07000 -2.29798 -0.05541 2.79645
Degrees of Freedom: 31 Total (i.e. Null); 27 Residual
Null Deviance: 1126
Residual Deviance: 219.5 AIC: 164.4
如果我想将 cyl6 设置为 -.34,将 cyl8 设置为 -1.4,然后重新运行以查看它如何影响其他变量,我该怎么做?
我想这就是你能做的
df$mpgCyl=df$mpg
df$mpgCyl[df$cyl==6]=df$mpgCyl[df$cyl==6]-0.34
df$mpgCyl[df$cyl==8]=df$mpgCyl[df$cyl==8]-1.4
model2=glm(mpgCyl ~ hp + gear, data = df)
> model2
Call: glm(formula = mpgCyl ~ hp + gear, data = df)
Coefficients:
(Intercept) hp gear
16.86483 -0.07146 3.53128
更新评论:
cyl
是一个因素,因此默认情况下它对 glm
的贡献是偏移量,而不是斜率。实际上 cyl==4
是 'hidden' 但也存在于 glm
中。所以在你的第一个 glm 中,模型说的是:
1) for cyl==4: mpg=19.8-0.055*hp+2.79*gear
2) for cyl==6: mpg=(19.8-4.07)-0.055*hp+2.79*gear
3) for cyl==8: mpg=(19.8-2.29)-0.055*hp+2.79*gear
也许你也可以在这里查看https://stats.stackexchange.com/questions/213710/level-of-factor-taken-as-intercept and here Is there any way to fit a `glm()` so that all levels are included (i.e. no reference level)?
希望对您有所帮助
谁能解释一下如何在 r 中为不同级别的分类变量设置常量?
我已阅读以下内容:How to set the Coefficient Value in Regression; R 它很好地解释了如何为整个分类变量设置常量。我想知道如何为每个级别设置一个。
例如,让我们看一下 MTCARS 数据集:
df <- as.data.frame(mtcars)
df$cyl <- as.factor(df$cyl)
set.seed(1)
glm(mpg ~ cyl + hp + gear, data = df)
这给了我以下输出:
Call: glm(formula = mpg ~ cyl + hp + gear, data = df)
Coefficients:
(Intercept) cyl6 cyl8 hp gear
19.80268 -4.07000 -2.29798 -0.05541 2.79645
Degrees of Freedom: 31 Total (i.e. Null); 27 Residual
Null Deviance: 1126
Residual Deviance: 219.5 AIC: 164.4
如果我想将 cyl6 设置为 -.34,将 cyl8 设置为 -1.4,然后重新运行以查看它如何影响其他变量,我该怎么做?
我想这就是你能做的
df$mpgCyl=df$mpg
df$mpgCyl[df$cyl==6]=df$mpgCyl[df$cyl==6]-0.34
df$mpgCyl[df$cyl==8]=df$mpgCyl[df$cyl==8]-1.4
model2=glm(mpgCyl ~ hp + gear, data = df)
> model2
Call: glm(formula = mpgCyl ~ hp + gear, data = df)
Coefficients:
(Intercept) hp gear
16.86483 -0.07146 3.53128
更新评论:
cyl
是一个因素,因此默认情况下它对 glm
的贡献是偏移量,而不是斜率。实际上 cyl==4
是 'hidden' 但也存在于 glm
中。所以在你的第一个 glm 中,模型说的是:
1) for cyl==4: mpg=19.8-0.055*hp+2.79*gear
2) for cyl==6: mpg=(19.8-4.07)-0.055*hp+2.79*gear
3) for cyl==8: mpg=(19.8-2.29)-0.055*hp+2.79*gear
也许你也可以在这里查看https://stats.stackexchange.com/questions/213710/level-of-factor-taken-as-intercept and here Is there any way to fit a `glm()` so that all levels are included (i.e. no reference level)?
希望对您有所帮助