如何为分类变量固定 R 中的系数

How to fix coefficients in R for categorical variables

我想知道如何在每个不同级别的分类变量模型中放置偏移量(或固定系数),并了解这如何影响其他变量。我不确定如何准确编码。

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)

谁能帮我弄清楚如何正确执行此操作?

在新的 R 会话中:

glm(mpg ~ offset(I(-4 * (cyl == 6) + -9 * (cyl == 8))) + hp, data = mtcars)
# Call:  glm(formula = mpg ~ offset(I(-4 * (cyl == 6) + -9 * (cyl == 8))) + 
#     hp, data = mtcars)
# 
# Coefficients:
# (Intercept)           hp  
#    27.66881     -0.01885  
# 
# Degrees of Freedom: 31 Total (i.e. Null);  30 Residual
# Null Deviance:        353.8 
# Residual Deviance: 302    AIC: 168.6