簡體   English   中英

在回歸中將分類變量與虛擬變量相乘

[英]Multiplying a categorical variable with a dummy in regression

我正在嘗試運行一個回歸,它的分數與一個女性假人(取值為 0 或 1)一起回歸,並且我也有那個女性的國家。 我正在嘗試對女性與國家/地區互動的回歸產生固定效果,但是我嘗試的每種方法都不起作用,因為我將數字乘以一個因子

我曾嘗試使用 fastdummies,但沒有奏效。 我也嘗試使用 country-1 方法,並嘗試與女性相乘但沒有成功。

#first wrong
olss1= lm(pv1math ~ female + I(ggi*female) + factor(country) +  factor(year) + I(female * factor(country)), data = f1)
# second wrong
olss1= lm(pv1math ~ female + I(ggi*female) + factor(country) +  factor(year) + factor( female * country ), data = f1)

錯誤消息是我不能將因數與數字相乘

公式中的 * 運算符將給出交互作用以及低階項。 這是一個例子:

country <- c("A", "A", "A", "B", "B", "B")
female <- c(1, 1, 0, 1, 0, 1)
y <- 1:6

fm <- lm(y ~ country * female)
fm

給予:

Call:
lm(formula = y ~ country * female)

Coefficients:
    (Intercept)         countryB           female  countryB:female  
            3.0              2.0             -1.5              1.5  

我們還可以檢查 model 矩陣

model.matrix(fm)

給予

  (Intercept) countryB female countryB:female
1           1        0      1               0
2           1        0      1               0
3           1        0      0               0
4           1        1      1               1
5           1        1      0               0
6           1        1      1               1
attr(,"assign")
[1] 0 1 2 3
attr(,"contrasts")
attr(,"contrasts")$country
[1] "contr.treatment"

你在這里不需要I() *單獨將執行交互,而I()將在回歸之前執行算術運算。

相比:

lm(pv1math ~ ggi*female, data=dat)$coefficients
# (Intercept)         ggi      female  ggi:female 
#         ...         ...         ...         ... 

lm(pv1math ~ I(ggi*female), data=dat)$coefficients
# (Intercept) I(ggi * female) 
#         ...             ... 

I()對於多項式很有用,其中年齡是一個流行的候選者: pv1math ~ age + I(age^2) + I(age^3) ,或者對 GLM 中的因變量進行二值化: glm(I(pv1math > 0.75) ~ ggi*female, family=binomial)

而且-正如@G.Grothendieck已經寫的那樣-您不需要重復交互項中已經存在的變量(這只是多余的),因此您可能想嘗試:

lm(pv1math ~ ggi*female + factor(year) + female*factor(country), data=f1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM