Teoría

lm() Es la función en R para ajustar modelos lineales Es el modelo estadístico mas básico que existe, y más facil de interpretar.
Para interpretarlo se usa la función R-cuadrada, que significa qué tan cerca están los datos de la regresión. Va de 0 a 1, donde 1 es el que el modelo explica toda la variabilidad.

Contexto

Se cuenta con un registro de propiedades residenciales con sus características físicas y de ubicación. Se desea generar un modelo predictivo para el precio de las casas.

Instalar paquetes y llamar librerías

#install.packages("corrplot")
library(corrplot)
## corrplot 0.95 loaded

Subir archivo

# file.choose()
df <- read.csv("/Users/danaraesparzamacias/Desktop/HousePriceData.csv") 

Entender base de datos

summary(df)
##   Observation      Dist_Taxi      Dist_Market    Dist_Hospital  
##  Min.   :  1.0   Min.   :  146   Min.   : 1666   Min.   : 3227  
##  1st Qu.:237.0   1st Qu.: 6477   1st Qu.: 9367   1st Qu.:11302  
##  Median :469.0   Median : 8228   Median :11149   Median :13189  
##  Mean   :468.4   Mean   : 8235   Mean   :11022   Mean   :13091  
##  3rd Qu.:700.0   3rd Qu.: 9939   3rd Qu.:12675   3rd Qu.:14855  
##  Max.   :932.0   Max.   :20662   Max.   :20945   Max.   :23294  
##                                                                 
##      Carpet         Builtup           Parking      City_Category
##  Min.   :  775   Min.   :  932   Length   :905   Length   :905  
##  1st Qu.: 1317   1st Qu.: 1579   N.unique :  4   N.unique :  3  
##  Median : 1478   Median : 1774   N.blank  :  0   N.blank  :  0  
##  Mean   : 1511   Mean   : 1794   Min.nchar:  4   Min.nchar:  5  
##  3rd Qu.: 1654   3rd Qu.: 1985   Max.nchar: 12   Max.nchar:  5  
##  Max.   :24300   Max.   :12730                                  
##  NAs    :7                                                      
##     Rainfall       House_Price       
##  Min.   :-110.0   Min.   :  1492000  
##  1st Qu.: 600.0   1st Qu.:  4623000  
##  Median : 780.0   Median :  5860000  
##  Mean   : 786.9   Mean   :  6083992  
##  3rd Qu.: 970.0   3rd Qu.:  7200000  
##  Max.   :1560.0   Max.   :150000000  
## 
str(df)
## 'data.frame':    905 obs. of  10 variables:
##  $ Observation  : int  1 2 3 4 5 6 7 8 9 10 ...
##  $ Dist_Taxi    : int  9796 8294 11001 8301 10510 6665 13153 5882 7495 8233 ...
##  $ Dist_Market  : int  5250 8186 14399 11188 12629 5142 11869 9948 11589 7067 ...
##  $ Dist_Hospital: int  10703 12694 16991 12289 13921 9972 17811 13315 13370 11400 ...
##  $ Carpet       : int  1659 1461 1340 1451 1770 1442 1542 1261 1090 1030 ...
##  $ Builtup      : int  1961 1752 1609 1748 2111 1733 1858 1507 1321 1235 ...
##  $ Parking      : chr  "Open" "Not Provided" "Not Provided" "Covered" ...
##  $ City_Category: chr  "CAT B" "CAT B" "CAT A" "CAT B" ...
##  $ Rainfall     : int  530 210 720 620 450 760 1030 1020 680 1130 ...
##  $ House_Price  : int  6649000 3982000 5401000 5373000 4662000 4526000 7224000 3772000 4631000 4415000 ...
head(df)
##   Observation Dist_Taxi Dist_Market Dist_Hospital Carpet Builtup      Parking
## 1           1      9796        5250         10703   1659    1961         Open
## 2           2      8294        8186         12694   1461    1752 Not Provided
## 3           3     11001       14399         16991   1340    1609 Not Provided
## 4           4      8301       11188         12289   1451    1748      Covered
## 5           5     10510       12629         13921   1770    2111 Not Provided
## 6           6      6665        5142          9972   1442    1733         Open
##   City_Category Rainfall House_Price
## 1         CAT B      530     6649000
## 2         CAT B      210     3982000
## 3         CAT A      720     5401000
## 4         CAT B      620     5373000
## 5         CAT B      450     4662000
## 6         CAT B      760     4526000
tail(df,5) 
##     Observation Dist_Taxi Dist_Market Dist_Hospital Carpet Builtup Parking
## 901         928     12176        8518         15673   1582    1910 Covered
## 902         929      7214        8717         10553   1387    1663    Open
## 903         930      7423       11708         13220   1200    1436    Open
## 904         931     15082       14700         19617   1299    1560    Open
## 905         932      9297       12537         14418   1174    1429 Covered
##     City_Category Rainfall House_Price
## 901         CAT C     1080     6639000
## 902         CAT A      850     8208000
## 903         CAT A     1060     7644000
## 904         CAT B      770     9661000
## 905         CAT C     1110     5434000
#Tomar en cuenta solo variables numéricas en la matriz de correlación
df_num <- df[, sapply(df, is.numeric)]
correlacion <- cor(df_num, use = "complete.obs")
corrplot(correlacion)

Generar el modelo

regresion <- lm(House_Price ~ ., data = df_num)
summary(regresion)
## 
## Call:
## lm(formula = House_Price ~ ., data = df_num)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -4412613 -1228090  -100987  1275140  5529493 
## 
## Coefficients:
##                 Estimate Std. Error t value Pr(>|t|)    
## (Intercept)    3.283e+06  5.030e+05   6.526 1.14e-10 ***
## Observation    5.265e+02  2.118e+02   2.486   0.0131 *  
## Dist_Taxi      5.509e-01  3.730e+01   0.015   0.9882    
## Dist_Market    4.446e+01  2.888e+01   1.539   0.1241    
## Dist_Hospital  5.905e+01  4.178e+01   1.413   0.1579    
## Carpet         9.957e+03  1.979e+02  50.326  < 2e-16 ***
## Builtup       -7.694e+03  3.341e+02 -23.031  < 2e-16 ***
## Rainfall       7.183e+01  2.138e+02   0.336   0.7370    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1702000 on 890 degrees of freedom
##   (7 observations deleted due to missingness)
## Multiple R-squared:  0.8898, Adjusted R-squared:  0.8889 
## F-statistic:  1026 on 7 and 890 DF,  p-value: < 2.2e-16

Ajustar el modelo

regresion2 <- lm(House_Price ~ Dist_Taxi + Dist_Market + Dist_Hospital + Carpet + Builtup + Rainfall, data = df)
summary(regresion2) 
## 
## Call:
## lm(formula = House_Price ~ Dist_Taxi + Dist_Market + Dist_Hospital + 
##     Carpet + Builtup + Rainfall, data = df)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -4196767 -1205994   -77768  1277227  5655558 
## 
## Coefficients:
##                 Estimate Std. Error t value Pr(>|t|)    
## (Intercept)    3.576e+06  4.904e+05   7.293 6.68e-13 ***
## Dist_Taxi      1.119e+00  3.741e+01   0.030    0.976    
## Dist_Market    4.195e+01  2.895e+01   1.449    0.148    
## Dist_Hospital  6.108e+01  4.189e+01   1.458    0.145    
## Carpet         9.973e+03  1.983e+02  50.290  < 2e-16 ***
## Builtup       -7.734e+03  3.346e+02 -23.111  < 2e-16 ***
## Rainfall       6.721e+01  2.144e+02   0.313    0.754    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1707000 on 891 degrees of freedom
##   (7 observations deleted due to missingness)
## Multiple R-squared:  0.889,  Adjusted R-squared:  0.8883 
## F-statistic:  1189 on 6 and 891 DF,  p-value: < 2.2e-16

Generar predicciones

datos_nuevos <- data.frame(
  Dist_Taxi = 8000,
  Dist_Market = 10000,
  Dist_Hospital = 12000,
  Carpet = 1500,
  Builtup = 1800,
  Rainfall = 600
)

predict(regresion2, datos_nuevos) 
##       1 
## 5817366

Generar predicciones por escenarios

escenarios <- data.frame(
  Tipo = c("Económica", "Promedio", "Lujo"),
  Dist_Taxi = c(12000, 8000, 4000),
  Dist_Market = c(14000, 10000, 5000),
  Dist_Hospital = c(15000, 11000, 6000),
  Carpet = c(1000, 1500, 2200),
  Builtup = c(1200, 1800, 2600),
  Rainfall = c(700, 700, 700)
)

# Generar la nueva predicción 
escenarios$Precio_Estimado <- predict(regresion2, escenarios)
escenarios
##        Tipo Dist_Taxi Dist_Market Dist_Hospital Carpet Builtup Rainfall
## 1 Económica     12000       14000         15000   1000    1200      700
## 2  Promedio      8000       10000         11000   1500    1800      700
## 3      Lujo      4000        5000          6000   2200    2600      700
##   Precio_Estimado
## 1         5833209
## 2         5763003
## 3         6037679