datos

library(wooldridge)
data(hprice1)
head(force(hprice1),n=5)
##   price assess bdrms lotsize sqrft colonial   lprice  lassess llotsize   lsqrft
## 1   300  349.1     4    6126  2438        1 5.703783 5.855359 8.720297 7.798934
## 2   370  351.5     3    9903  2076        1 5.913503 5.862210 9.200593 7.638198
## 3   191  217.7     3    5200  1374        0 5.252274 5.383118 8.556414 7.225482
## 4   195  231.8     3    4600  1448        1 5.273000 5.445875 8.433811 7.277938
## 5   373  319.1     4    6095  2514        1 5.921578 5.765504 8.715224 7.829630

estimación del modelo

options(scipen = 9999)
# 1. Cargar datos
library(stargazer)
data(hprice1)

# 2. Estimación del modelo (Solo con las variables que te dio el profesor)
# R automáticamente buscará las columnas llamadas 'price', 'lotsize', 'sqrft' y 'bdrms'
modelo_lineal <- lm(price ~ lotsize + sqrft + bdrms, data = hprice1)

# 3. Ver resultados
stargazer(modelo_lineal,type ="text",title="modelo estimado")
## 
## modelo estimado
## ===============================================
##                         Dependent variable:    
##                     ---------------------------
##                                price           
## -----------------------------------------------
## lotsize                      0.002***          
##                               (0.001)          
##                                                
## sqrft                        0.123***          
##                               (0.013)          
##                                                
## bdrms                         13.853           
##                               (9.010)          
##                                                
## Constant                      -21.770          
##                              (29.475)          
##                                                
## -----------------------------------------------
## Observations                    88             
## R2                             0.672           
## Adjusted R2                    0.661           
## Residual Std. Error      59.833 (df = 84)      
## F Statistic           57.460*** (df = 3; 84)   
## ===============================================
## Note:               *p<0.1; **p<0.05; ***p<0.01

CALCULANDO EL ESTADISTICO DE WHITE manualmente

library(stargazer)
u_i<-modelo_lineal$residuals
data_prueba_white<-as.data.frame(cbind(u_i,hprice1))
regresion_auxiliar<-lm(I(u_i^2)~lotsize+sqrft+bdrms+I(lotsize^2)+I(sqrft^2)+I(bdrms^2)+lotsize*sqrft+lotsize*bdrms+sqrft*bdrms,data = data_prueba_white)
sumario<-summary(regresion_auxiliar)
n<-nrow(data_prueba_white)
R_2<-sumario$r.squared
LM_w<-n*R_2
gl=3+3+3
p_value<-1-pchisq(q = LM_w,df = gl)
VC<-qchisq(p = 0.95,df = gl)
salida_white<-c(LM_w,VC,p_value)
names(salida_white)<-c("LMw","Valor Crítico","p value")
stargazer(salida_white,title = "Resultados de la prueba de White",type = "text",digits = 7)
## 
## Resultados de la prueba de White
## ==================================
## LMw        Valor Crítico  p value 
## ----------------------------------
## 33.7316600  16.9189800   0.0000995
## ----------------------------------

#Regla valor critico, dado que Lmw=33.73 > 16.92=v.c entonces se rechaza Ho.

Calculo de la prueba white con lmtest

library(lmtest)
prueba_white <- bptest(modelo_lineal, 
                       ~ lotsize + sqrft + bdrms + 
                         I(lotsize^2) + I(sqrft^2) + I(bdrms^2) + 
                         lotsize*sqrft + lotsize*bdrms + sqrft*bdrms, 
                       data = hprice1)
print(prueba_white)
## 
##  studentized Breusch-Pagan test
## 
## data:  modelo_lineal
## BP = 33.732, df = 9, p-value = 0.00009953

#verificación regla de decisión.regla de p-value #Como 0.00099953<0.05 se se rechaza la H0, por lo tanto hay evidencia de que la varianza de los residuos es heterocedastica

GRÁFICO DE LA PRUEBA WHITE

library(fastGraph)

# 1. Parámetros básicos
alpha_sig <- 0.05
gl_val <- 9 
VC <- qchisq(1 - alpha_sig, df = gl_val) # Esto es 16.919
LMw_val <- as.numeric(salida_white["LMw"])

# 2. Definir el límite del gráfico (Eje X)
# Forzamos a que el gráfico llegue al menos hasta 25 para que se vea la cola
limite_x <- max(25, LMw_val + 5)

# 3. Gráfica con sombreado
shadeDist( xshade = VC, 
           ddist = "dchisq", 
           parm1 = gl_val, 
           lower.tail = FALSE, 
           col = c("black", "red"), 
           xmin = 0,
           xmax = limite_x, # Esto asegura que la zona roja se vea
           main = "Prueba de White",
           sub = "" # Quitamos el sub para ponerlo más claro
           )

# 4. Líneas verticales para identificar los puntos clave
abline(v = VC, col = "red", lwd = 2, lty = 2)      # Línea en el Valor Crítico
abline(v = LMw_val, col = "blue", lwd = 3)         # Línea en tu Estadístico

# 5. Etiquetas de texto con los valores reales
# Ponemos el valor numérico justo encima de las líneas
text(x = VC, y = 0.04, labels = paste("VC:", round(VC, 4)), col = "red", font = 2, pos = 2)
text(x = LMw_val, y = 0.06, labels = paste("Lmw:", round(LMw_val, 3)), col = "blue", font = 1, pos = 2)

#7. decir si se rechaza o se aprueba la hipotesis 
if (LMw_val > VC) {
  print("Resultado: RECHAZO H0. Hay evidencia de Heterocedasticidad.\n")
} else {
  print("Resultado: NO RECHAZO H0. Los errores son Homocedásticos.\n")
}
## [1] "Resultado: RECHAZO H0. Hay evidencia de Heterocedasticidad.\n"

Prueba de Durbin Watson

library(lmtest)
dwtest(modelo_lineal,alternative="two.sided",iterations = 1000)
## 
##  Durbin-Watson test
## 
## data:  modelo_lineal
## DW = 2.1098, p-value = 0.6218
## alternative hypothesis: true autocorrelation is not 0

PRUEBA DW CON LIBRERIA CAR

library(car)
durbinWatsonTest(modelo_lineal,simulate= TRUE,reps=1000)
##  lag Autocorrelation D-W Statistic p-value
##    1     -0.05900522      2.109796   0.642
##  Alternative hypothesis: rho != 0

AUTOCORRELACIÓN DE ORDEN SUPERIOR(orden “m”)

library(dplyr)
## 
## Adjuntando el paquete: 'dplyr'
## The following object is masked from 'package:car':
## 
##     recode
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(tidyr)
library(stargazer)
library(kableExtra)
## 
## Adjuntando el paquete: 'kableExtra'
## The following object is masked from 'package:dplyr':
## 
##     group_rows
cbind(u_i,hprice1)|> as.data.frame() |> 
  mutate(Lag_1=dplyr::lag(u_i,1)) |> #cada vez que perdemos un lag perdemos observa.
replace_na(list(Lag_1=0)) -> data_prueba_BG
kable(head(data_prueba_BG, n=6))
u_i price assess bdrms lotsize sqrft colonial lprice lassess llotsize lsqrft Lag_1
-45.639765 300.000 349.1 4 6126 2438 1 5.703783 5.855359 8.720297 7.798934 0.000000
74.848732 370.000 351.5 3 9903 2076 1 5.913503 5.862210 9.200593 7.638198 -45.639765
-8.236558 191.000 217.7 3 5200 1374 0 5.252274 5.383118 8.556414 7.225481 74.848732
-12.081520 195.000 231.8 3 4600 1448 1 5.273000 5.445875 8.433811 7.277938 -8.236558
18.093192 373.000 319.1 4 6095 2514 1 5.921578 5.765504 8.715224 7.829630 -12.081520
62.939597 466.275 414.5 5 8566 2754 1 6.144775 6.027073 9.055556 7.920810 18.093192
reg_aux_BG<-lm(u_i~assess+bdrms+sqrft+Lag_1,data=data_prueba_BG)
resumen_BG<-summary(reg_aux_BG)
n<-nrow(hprice1)
gl<-1 #orden de correlación
R_2_BG<-resumen_BG$r.squared
LM_BG<-n*R_2_BG
VC<-qchisq(p=0.05, lower.tail=FALSE,df=gl)
p_value_BG<-pchisq(q=LM_BG, lower.tail=FALSE,df=gl)
salida_BG<-c(LM_BG,VC,p_value_BG)
names(salida_BG)<-c("LM_BG","Valor critico","p-value")
stargazer(salida_BG,title= "Prueba GB", type= "html",digits = 6)
Prueba GB
LM_BG Valor critico p-value
38.492620 3.841459 0

preparacion de datos

cbind(u_i,hprice1) %>% 
  as.data.frame() %>% 
  mutate(Lag_1=dplyr::lag(u_i,1),
         Lag_2=dplyr::lag(u_i,2)) %>% 
  replace_na(list(Lag_1=0,Lag_2=0))->data_prueba_BG
kable(head(data_prueba_BG,6))
u_i price assess bdrms lotsize sqrft colonial lprice lassess llotsize lsqrft Lag_1 Lag_2
-45.639765 300.000 349.1 4 6126 2438 1 5.703783 5.855359 8.720297 7.798934 0.000000 0.000000
74.848732 370.000 351.5 3 9903 2076 1 5.913503 5.862210 9.200593 7.638198 -45.639765 0.000000
-8.236558 191.000 217.7 3 5200 1374 0 5.252274 5.383118 8.556414 7.225481 74.848732 -45.639765
-12.081520 195.000 231.8 3 4600 1448 1 5.273000 5.445875 8.433811 7.277938 -8.236558 74.848732
18.093192 373.000 319.1 4 6095 2514 1 5.921578 5.765504 8.715224 7.829630 -12.081520 -8.236558
62.939597 466.275 414.5 5 8566 2754 1 6.144775 6.027073 9.055556 7.920810 18.093192 -12.081520

calculando el auxiliar

regresion_auxiliar_BG<-lm(u_i ~ lotsize + sqrft + bdrms + Lag_1 + Lag_2, data = data_prueba_BG)
sumario_BG<-summary(regresion_auxiliar_BG)
R_2_BG<-sumario_BG$r.squared
n<-nrow(data_prueba_BG)
LM_BG<-n*R_2_BG
gl=2
p_value<-1-pchisq(q = LM_BG,df = gl)
VC<-qchisq(p = 0.95,df = gl)
salida_bg<-c(LM_BG,VC,p_value)
names(salida_bg)<-c("LMbg","Valor Crítico","p value")
stargazer(salida_bg,title = "Resultados de la prueba de Breusch Godfrey",type = "text",digits = 6)
## 
## Resultados de la prueba de Breusch Godfrey
## ===============================
## LMbg     Valor Crítico p value 
## -------------------------------
## 3.033403   5.991465    0.219435
## -------------------------------

#usando la libreria lmtest

library(lmtest)
bgtest(modelo_lineal,order = 2)
## 
##  Breusch-Godfrey test for serial correlation of order up to 2
## 
## data:  modelo_lineal
## LM test = 3.0334, df = 2, p-value = 0.2194