在R

时间:2018-12-25 13:09:24

标签: r linear-regression dummy-variable

我有一个要添加到面板线性模型中的分类自变量(选项为“是”或“否”)。根据  在这里回答:After generating dummy variables?,lm函数会自动为您创建虚拟变量作为分类变量。

这是否意味着不需要通过dummy.data.frame创建虚拟变量,我只需在plm函数中添加变量,它将自动被视为虚拟变量(即使数据不是数字形式) )?这与plm函数是否相同?

此外,我没有多少数据可以作为开始。如果我在不创建虚拟变量的情况下将数据手动转换为数字(即“ yes” = 1,“ no” = 0)会不会很受伤?

1 个答案:

答案 0 :(得分:0)

没有必要创建用于lm()函数的伪变量。为了说明这一点,我们将使用mtcars(0 =自动,1 =手动传输)作为因子变量,对am数据集运行回归模型。

summary(lm(mpg ~ wt + factor(am),data=mtcars))

...以及输出:

> summary(lm(mpg ~ wt + factor(am),data=mtcars))

Call:
lm(formula = mpg ~ wt + factor(am), data = mtcars)

Residuals:
    Min      1Q  Median      3Q     Max 
-4.5295 -2.3619 -0.1317  1.4025  6.8782 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) 37.32155    3.05464  12.218 5.84e-13 ***
wt          -5.35281    0.78824  -6.791 1.87e-07 ***
factor(am)1 -0.02362    1.54565  -0.015    0.988    
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 3.098 on 29 degrees of freedom
Multiple R-squared:  0.7528,    Adjusted R-squared:  0.7358 
F-statistic: 44.17 on 2 and 29 DF,  p-value: 1.579e-09