Prévia do material em texto
Estimação por MQO 2022-11-22 #library(tinytex) Vamos começar com o Modelo de regressão linear: yi = β1 + β2x1i + ... + βkxki + ϵi, i = 2, ..., N A função lm() estima esse modelo pelo método de mínimos quadrados ordinários (MQO). Na função lm(), é obrigatório passar-se um objeto da classe fórmula, ou algum objeto que possa ser convertido para uma fórmula. Por exemplo, para o modelo linear com duas variáveis (y e x) e uma constante, a fórmula corre- spondente é: f <- 'y ~ x' class(f) Para facilitar a manipulação da base de dados vamos chamar library(dplyr) library(dplyr) Carregando a base de dados de mtcars. A base traz o consumo de gasolina (mpg) e algumas outras características do veículo. Você pode olhar o help dessa base: ?mtcars. Como a base já está incorporada no R, basta usar os comandos seguintes: data(mtcars) head(mtcars) ## mpg cyl disp hp drat wt qsec vs am gear carb ## Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 ## Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 ## Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 ## Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 ## Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 ## Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 #?mtcars Ao usar a ?mtcars temos acesso às informações da base. • mpg: Miles/(US) gallon • cyl: Number of cylinders • disp: Displacement (cu.in.) 1 • hp: Gross horsepower • drat: Rear axle ratio • wt: Weight (1000 lbs) • qsec: 1/4 mile time • vs: Engine (0 = V-shaped, 1 = straight) • am: Transmission (0 = automatic, 1 = manual) • gear: Number of forward gears • carb: Number of carburetors str(mtcars) ## ’data.frame’: 32 obs. of 11 variables: ## $ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ... ## $ cyl : num 6 6 4 6 8 6 8 4 4 6 ... ## $ disp: num 160 160 108 258 360 ... ## $ hp : num 110 110 93 110 175 105 245 62 95 123 ... ## $ drat: num 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ... ## $ wt : num 2.62 2.88 2.32 3.21 3.44 ... ## $ qsec: num 16.5 17 18.6 19.4 17 ... ## $ vs : num 0 0 1 1 0 1 0 1 1 1 ... ## $ am : num 1 1 1 0 0 0 0 0 0 0 ... ## $ gear: num 4 4 4 3 3 3 3 4 4 4 ... ## $ carb: num 4 4 1 1 2 1 4 2 2 4 ... #glimpse(mtcars) plot(mtcars$mpg, mtcars$hp, xlab="Milhas por galão (mpg)", ylab="Cavalos-vapor (hp)") 2 10 15 20 25 30 50 10 0 15 0 20 0 25 0 30 0 Milhas por galão (mpg) C av al os − va po r (h p) Estimação por OLS. Vamos estimar o seguinte modelo simples. mpg = β1 + β2hp + ... + ϵ, i = 2, ..., N Para estimar por MQO usamos lm() lm(mpg ~ hp, data = mtcars) ## ## Call: ## lm(formula = mpg ~ hp, data = mtcars) ## ## Coefficients: ## (Intercept) hp ## 30.09886 -0.06823 Agora vamos estimar o seguinte modelo com mais de uma variável. mpgi = β1 + β2hp + β3wt... + ϵ, i = 2, ..., N 3 plot(mtcars$mpg, mtcars$wt, xlab="Milhas por galão (mpg)", ylab="Libras (wt)") 10 15 20 25 30 2 3 4 5 Milhas por galão (mpg) Li br as ( w t) Estimação #Rodando a regressão e guardando com o nome fit_ols1 fit_ols1 = lm(formula = mpg ~ hp + wt, data = mtcars) #resumindo os resultados summary(fit_ols1) ## ## Call: ## lm(formula = mpg ~ hp + wt, data = mtcars) ## ## Residuals: ## Min 1Q Median 3Q Max ## -3.941 -1.600 -0.182 1.050 5.854 ## ## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 37.22727 1.59879 23.285 < 2e-16 *** ## hp -0.03177 0.00903 -3.519 0.00145 ** ## wt -3.87783 0.63273 -6.129 1.12e-06 *** ## --- ## Signif. codes: 0 ’***’ 0.001 ’**’ 0.01 ’*’ 0.05 ’.’ 0.1 ’ ’ 1 ## 4 ## Residual standard error: 2.593 on 29 degrees of freedom ## Multiple R-squared: 0.8268, Adjusted R-squared: 0.8148 ## F-statistic: 69.21 on 2 and 29 DF, p-value: 9.109e-12 Melhorando a apresentação de resultados com stargazer #install.packages("stargazer") library(stargazer) stargazer(fit_ols1, type="text", title = "Coeficientes estimados") ## ## Coeficientes estimados ## =============================================== ## Dependent variable: ## --------------------------- ## mpg ## ----------------------------------------------- ## hp -0.032*** ## (0.009) ## ## wt -3.878*** ## (0.633) ## ## Constant 37.227*** ## (1.599) ## ## ----------------------------------------------- ## Observations 32 ## R2 0.827 ## Adjusted R2 0.815 ## Residual Std. Error 2.593 (df = 29) ## F Statistic 69.211*** (df = 2; 29) ## =============================================== ## Note: *p<0.1; **p<0.05; ***p<0.01 Extraindo informações especificas da regressão. #Informações das estimativas de duas formas fit_ols1$coefficients ## (Intercept) hp wt ## 37.22727012 -0.03177295 -3.87783074 summary(fit_ols1)$coefficients ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 37.22727012 1.59878754 23.284689 2.565459e-20 ## hp -0.03177295 0.00902971 -3.518712 1.451229e-03 ## wt -3.87783074 0.63273349 -6.128695 1.119647e-06 5 #Informações dos valores ajustados e dos resíduos. head(fit_ols1$fitted.values) ## Mazda RX4 Mazda RX4 Wag Datsun 710 Hornet 4 Drive ## 23.57233 22.58348 25.27582 21.26502 ## Hornet Sportabout Valiant ## 18.32727 20.47382 head(fit_ols1$residuals) ## Mazda RX4 Mazda RX4 Wag Datsun 710 Hornet 4 Drive ## -2.5723294 -1.5834826 -2.4758187 0.1349799 ## Hornet Sportabout Valiant ## 0.3727334 -2.3738163 Incluindo variáveis categoricas no Modelo Criamos dummies para incluir as variáveis categóricas e o RStudio automaticamente reconhece e exclui uma dummie para evitar problemas de multicolinearidade. Transformamos a variável cyl com valores (4, 6, 8) em dummie com factor. mtcars_factor1 = mtcars %>% mutate(cyl = factor(cyl)) summary( lm(mpg ~ cyl, data=mtcars_factor1) )$coef ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 26.663636 0.9718008 27.437347 2.688358e-22 ## cyl6 -6.920779 1.5583482 -4.441099 1.194696e-04 ## cyl8 -11.563636 1.2986235 -8.904534 8.568209e-10 Observe que foi excluída uma dummie e só temos informação de cyl6 e de cyl8 Exportando a código latex stargazer::stargazer(fit_ols1) ## ## % Table created by stargazer v.5.2.3 by Marek Hlavac, Social Policy Institute. E-mail: marek.hlavac at gmail.com ## % Date and time: seg, nov 28, 2022 - 17:25:57 ## \begin{table}[!htbp] \centering ## \caption{} ## \label{} ## \begin{tabular}{@{\extracolsep{5pt}}lc} ## \\[-1.8ex]\hline ## \hline \\[-1.8ex] ## & \multicolumn{1}{c}{\textit{Dependent variable:}} \\ ## \cline{2-2} ## \\[-1.8ex] & mpg \\ ## \hline \\[-1.8ex] ## hp & $-$0.032$^{***}$ \\ ## & (0.009) \\ 6 ## & \\ ## wt & $-$3.878$^{***}$ \\ ## & (0.633) \\ ## & \\ ## Constant & 37.227$^{***}$ \\ ## & (1.599) \\ ## & \\ ## \hline \\[-1.8ex] ## Observations & 32 \\ ## R$^{2}$ & 0.827 \\ ## Adjusted R$^{2}$ & 0.815 \\ ## Residual Std. Error & 2.593 (df = 29) \\ ## F Statistic & 69.211$^{***}$ (df = 2; 29) \\ ## \hline ## \hline \\[-1.8ex] ## \textit{Note:} & \multicolumn{1}{r}{$^{*}$p$<$0.1; $^{**}$p$<$0.05; $^{***}$p$<$0.01} \\ ## \end{tabular} ## \end{table} texreg::texreg(fit_ols1) ## ## \begin{table} ## \begin{center} ## \begin{tabular}{l c} ## \hline ## & Model 1 \\ ## \hline ## (Intercept) & $37.23^{***}$ \\ ## & $(1.60)$ \\ ## hp & $-0.03^{**}$ \\ ## & $(0.01)$ \\ ## wt & $-3.88^{***}$ \\ ## & $(0.63)$ \\ ## \hline ## R$^2$ & $0.83$ \\ ## Adj. R$^2$ & $0.81$ \\ ## Num. obs. & $32$ \\ ## \hline ## \multicolumn{2}{l}{\scriptsize{$^{***}p<0.001$; $^{**}p<0.01$; $^{*}p<0.05$}} ## \end{tabular} ## \caption{Statistical models} ## \label{table:coefficients} ## \end{center} ## \end{table} 7 Carregando a base de dados de mtcars. Estimação por OLS.