【问题标题】:Multiplying a categorical variable with a dummy in regression在回归中将分类变量与虚拟变量相乘
【发布时间】:2019-11-04 00:04:16
【问题描述】:

我正在尝试使用女性假人(取值为 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)

错误信息是我不能将因数与数字相乘

【问题讨论】:

  • 一般来说,发布错误消息是不够的。发布到 SO 示例时应该是可重现的,这意味着提供所需的完整代码和数据,以便其他任何人都可以将其复制并粘贴到他们的 R 会话中并获得相同的错误消息。请参阅r 标签页顶部的说明。

标签: r regression dummy-variable


【解决方案1】:

公式中的 * 运算符将给出交互作用以及低阶项。这是一个例子:

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.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"

【讨论】:

    【解决方案2】:

    这里不需要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() 很有用,例如对于多项式,其中 age 是一个受欢迎的候选者:pv1math ~ age + I(age^2) + I(age^3),或者对 GLM 中的因变量进行二值化:glm(I(pv1math &gt; 0.75) ~ ggi*female, family=binomial)

    而且 - as @G.Grothendieck already wrote - 你不需要重复交互项中已经存在的变量(这只是多余的),所以你可能想尝试一下:

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

    【讨论】:

      猜你喜欢
      • 2014-12-24
      • 2021-04-27
      • 2018-11-16
      • 2018-01-20
      • 1970-01-01
      • 2021-01-01
      • 2014-01-27
      • 2018-06-27
      • 2020-07-25
      相关资源
      最近更新 更多