[英]How `lm()` behaves when we remove intercept with multiple categorical predictors
[英]How does lm() know which predictors are categorical?
通常情況下,我和你(假設你不是機器人)很容易識別預測變量是分類的還是定量的 。 例如,性別顯然是明確的。 您的上次投票可以分類。
基本上,我們可以輕松識別分類預測變量。 但是當我們在R
輸入一些數據時會發生什么,並且它的lm
函數會為預測變量生成虛擬變量? 它是如何做到的?
關於StackOverflow的一些相關問題 。
搜索R factor
函數。 這是一個小型演示,第一個模型使用數量的圓柱作為數值有價值。 第二個模型將其用作分類變量。
> summary(lm(mpg~cyl,mtcars))
Call:
lm(formula = mpg ~ cyl, data = mtcars)
Residuals:
Min 1Q Median 3Q Max
-4.9814 -2.1185 0.2217 1.0717 7.5186
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 37.8846 2.0738 18.27 < 2e-16 ***
cyl -2.8758 0.3224 -8.92 6.11e-10 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 3.206 on 30 degrees of freedom
Multiple R-squared: 0.7262, Adjusted R-squared: 0.7171
F-statistic: 79.56 on 1 and 30 DF, p-value: 6.113e-10
> summary(lm(mpg~factor(cyl),mtcars))
Call:
lm(formula = mpg ~ factor(cyl), data = mtcars)
Residuals:
Min 1Q Median 3Q Max
-5.2636 -1.8357 0.0286 1.3893 7.2364
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 26.6636 0.9718 27.437 < 2e-16 ***
factor(cyl)6 -6.9208 1.5583 -4.441 0.000119 ***
factor(cyl)8 -11.5636 1.2986 -8.905 8.57e-10 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 3.223 on 29 degrees of freedom
Multiple R-squared: 0.7325, Adjusted R-squared: 0.714
F-statistic: 39.7 on 2 and 29 DF, p-value: 4.979e-09
當分類變量存儲為數字時,Hxd1011解決了更為困難的情況,因此默認情況下R理解它是一個數值 - 如果這不是理想的行為,我們必須使用factor
函數。
您在數據集Carseats
使用預測器ShelveLoc
示例更容易,因為它是一個文本(字符)變量,因此它只能是一個分類變量。
> head(Carseats$ShelveLoc)
[1] Bad Good Medium Medium Bad Bad
Levels: Bad Good Medium
R從特征類型決定那個東西。 您可以使用str(dataset)檢查它。如果該特征是因子類型,那么它將為該特征創建虛擬對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.