【问题标题】:How to fix coefficients in R for categorical variables如何在 R 中为分类变量固定系数
【发布时间】: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(&gt;|t|)
(Intercept) 28.65012 1.58779 18.044 &lt; 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 &lt;- glm(mpg ~ hp + I(-4 * cyl == 6), data = mtcars)
  • 你去掉了 offset() 部分。

标签: r offset


【解决方案1】:

在新的 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

【讨论】:

    猜你喜欢
    • 2011-05-26
    • 1970-01-01
    • 2022-11-11
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    • 2022-07-27
    相关资源
    最近更新 更多