[英]How `lm()` behaves when we remove intercept with multiple categorical predictors
我有兩個二元預測變量( name
和Treat
)。 我從整個 model ( value ~ name*Treat-1
) 中刪除了截距。
因此,我希望lm()
不會將我的任何二元預測變量中的任何類別作為參考類別。
對於預測器name
,我的期望與 output 匹配(即,沒有name
類別被視為參考類別)。
但是對於我的第二個二元預測器(即Treat
),它的一個類別(即"Treat-0.5"
)再次被視為參考類別。
我想知道當我們使用多個分類預測變量刪除截距時lm()
的行為如何?
dat <- read.csv('https://raw.githubusercontent.com/hkil/m/master/mv.l.csv')
dat$Treat <- factor(dat$Treat)
lm(value ~ name*Treat-1,data = dat)
coef(summary(m))
Estimate Std. Error t value Pr(>|t|)
nameY1 45.69318724 0.5132694 89.02378209 0.000000e+00
nameY2 45.97807164 0.5132694 89.57882078 0.000000e+00
Treat0.5 8.72325383 0.7258726 12.01760985 6.540707e-32
nameY2:Treat0.5 -0.09756526 1.0265389 -0.09504293 9.242927e-01
我預計 output 是:
Estimate Std. Error t value Pr(>|t|)
nameY1 45.69318724 0.5132694 89.02378209 0.000000e+00
nameY2 45.97807164 0.5132694 89.57882078 0.000000e+00
nameY1:Treat0.5 8.72325383 0.7258726 12.01760985 6.540707e-32
nameY2:Treat-0.5 8.625689 xxxxxxxxx xxxxxxxxxxx xxxxxxxxxxxx
要執行線性回歸:
lm()
function 使用由model.matrix()
創建的 model 矩陣 X 的 QR 分解(參見lm 幫助頁面) 為了得到一個解,它要求矩陣是滿秩的,基本上沒有冗余的預測列。
因此,即使您用-1
表示沒有截距, model.matrix()
也需要確保 model 矩陣是滿秩的,以便 QR 分解可以工作。 我們可以將您的示例簡化為:
value ~ name + Treat
假設我們有 name == Y1、name == Y2、Treat == 0.5、Treat == -0.5 的預測變量:
dummy_matrix = cbind(model.matrix(~name-1,data=dat),
model.matrix(~Treat-1,data=dat))
head(dummy_matrix)
nameY1 nameY2 Treat-0.5 Treat0.5
1 1 0 1 0
2 0 1 1 0
3 1 0 1 0
4 0 1 1 0
5 1 0 1 0
6 0 1 1 0
要預測 Y1 和 Treat-0.5,它將是 1 nameY1 + 0 nameY2 + 1 Treat-0.5 + 0 Treat0.5。 最后一個預測變量是多余的,因為預測變量 Treat-0.5 應該是組Treat-0.5
和Treat-0.5
的兩個平均值之間的差。
如果我們檢查排名,它當然比列數少一:
qr(dummy_matrix)$rank
[1] 3
如果你適合它,你會得到最后一列的 NA:
lm(dat$value ~ 0+dummy_matrix)
Call:
lm(formula = dat$value ~ 0 + dummy_matrix)
Coefficients:
dummy_matrixnameY1 dummy_matrixnameY2 dummy_matrixTreat-0.5
54.392 54.628 -8.674
dummy_matrixTreat0.5
NA
因此,如果您有超過 1 個分類預測器,從第 2 個分類預測器開始,其中一個將被設置為參考,以確保您的 model 矩陣是滿秩的,並且可以通過 QR 分解來求解。
您還可以查看這篇文章,該文章通過示例討論什么是對比矩陣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.