【发布时间】:2018-03-26 19:49:00
【问题描述】:
我想知道如何在模型中为每个不同级别的分类变量放置偏移量(或固定系数),并看看它如何影响其他变量。我不确定如何准确编码。
library(tidyverse)
mtcars <- as_tibble(mtcars)
mtcars$cyl <- as.factor(mtcars$cyl)
model1 <- glm(mpg ~ cyl + hp, data = mtcars)
summary(model1)
这给出了以下内容:
Call:
glm(formula = mpg ~ cyl + hp, data = mtcars)
Deviance Residuals:
Min 1Q Median 3Q Max
-4.818 -1.959 0.080 1.627 6.812
Coefficients:
Estimate Std. Error t value Pr(>|t|)(Intercept) 28.65012 1.58779 18.044 < 2e-16 ***
cyl6 -5.96766 1.63928 -3.640 0.00109 **
cyl8 -8.52085 2.32607 -3.663 0.00103 **
hp -0.02404 0.01541 -1.560 0.12995---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
(Dispersion parameter for gaussian family taken to be 9.898847)
`Null deviance: 1126.05 on 31 degrees of freedom`
Residual deviance: 277.17 on 28 degrees of freedom
AIC: 169.9
Number of Fisher Scoring iterations: 2
我想将气缸设置为不同的偏移量,例如将 6 个气缸设置为 -4 并将 8 个气缸设置为 -9,这样我就可以看到这对马力有什么影响。我在下面的代码中尝试了这个,但得到了一个错误,所以我不确定在分类变量中执行一个唯一值的正确方法远少于一个。
model2 <- glm(mpg ~ offset(I(-4 * cyl[6]))+ hp, data = mtcars)
谁能帮我弄清楚如何正确地做到这一点?
【问题讨论】:
-
cyl[6]是cyl的第六个值。相反,请尝试I(-4 * cyl == 6)或I(-4 * (cyl == 6) - 9 * (cyl == 8))以获得完整案例。 -
试过了。得到这个
Error in glm.fit(x = numeric(0), y = numeric(0), weights = NULL, start = NULL, : object 'fit' not found -
为我工作...
-
这就是我所拥有的。你看有什么不对吗?
model2 <- glm(mpg ~ hp + I(-4 * cyl == 6), data = mtcars) -
你去掉了
offset()部分。