【问题标题】:Extract root of dummy variable in model fit summary在模型拟合摘要中提取虚拟变量的根
【发布时间】:2019-04-01 18:42:13
【问题描述】:

在以下示例中,gender 被编码为与类别对应的虚拟变量。

fit <- lm(mass ~ height + gender, data=dplyr::starwars)
summary(fit)

# Call:
#   lm(formula = mass ~ height + gender, data = dplyr::starwars)
# 
# Residuals:
#   Min      1Q  Median      3Q     Max 
# -41.908  -6.536  -1.585   1.302  55.481 
# 
# Coefficients:
#   Estimate Std. Error t value Pr(>|t|)    
# (Intercept)          -46.69901   12.67896  -3.683 0.000557 ***
#   height                 0.59177    0.06784   8.723  1.1e-11 ***
#   genderhermaphrodite 1301.13951   17.37871  74.870  < 2e-16 ***
#   gendermale            22.39565    5.82763   3.843 0.000338 ***
#   gendernone            68.34530   17.49287   3.907 0.000276 ***
#   ---
#   Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
# 
# Residual standard error: 16.57 on 51 degrees of freedom
# (31 observations deleted due to missingness)
# Multiple R-squared:  0.9915,  Adjusted R-squared:  0.9909 
# F-statistic:  1496 on 4 and 51 DF,  p-value: < 2.2e-16

有没有办法提取虚拟变量名的根?例如,对于gendernonegendermalegenderhermaphrodite,根为gender,对应于dplyr::starwars 数据中的原始列名。

【问题讨论】:

  • 试试attr(fit$terms, "term.labels"),这将返回公式中使用的所有回归量的字符向量。

标签: r regression dummy-variable


【解决方案1】:

从公式中获取变量名并检查哪个与输入匹配:

input <- c("gendermale", "height")

v <- all.vars(formula(fit))
v[sapply(input, function(x) which(pmatch(v, x) == 1))]
## [1] "gender" "height"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    • 2018-07-07
    • 2019-03-26
    • 2012-11-07
    • 1970-01-01
    • 2021-02-23
    相关资源
    最近更新 更多