Cargar bases de datos

# Cargar Conjunto de Datos 1
data1 <- read.csv("https://raw.githubusercontent.com/geovannychoez/prueba/master/MTCars.csv", header = TRUE)
# Cargar Conjunto de Datos 2
data2 <- read.csv("https://raw.githubusercontent.com/geovannychoez/prueba/master/UsedCars.csv", header = TRUE)

Verifica que los datos se hayan cargado correctamente Data 1

head(data1) 
##   car_ID symboling                  CarName fueltype aspiration doornumber
## 1      1         3       alfa-romero giulia      gas        std        two
## 2      2         3      alfa-romero stelvio      gas        std        two
## 3      3         1 alfa-romero Quadrifoglio      gas        std        two
## 4      4         2              audi 100 ls      gas        std       four
## 5      5         2               audi 100ls      gas        std       four
## 6      6         2                 audi fox      gas        std        two
##       carbody drivewheel enginelocation wheelbase carlength carwidth carheight
## 1 convertible        rwd          front      88.6     168.8     64.1      48.8
## 2 convertible        rwd          front      88.6     168.8     64.1      48.8
## 3   hatchback        rwd          front      94.5     171.2     65.5      52.4
## 4       sedan        fwd          front      99.8     176.6     66.2      54.3
## 5       sedan        4wd          front      99.4     176.6     66.4      54.3
## 6       sedan        fwd          front      99.8     177.3     66.3      53.1
##   curbweight enginetype cylindernumber enginesize fuelsystem boreratio stroke
## 1       2548       dohc           four        130       mpfi      3.47   2.68
## 2       2548       dohc           four        130       mpfi      3.47   2.68
## 3       2823       ohcv            six        152       mpfi      2.68   3.47
## 4       2337        ohc           four        109       mpfi      3.19   3.40
## 5       2824        ohc           five        136       mpfi      3.19   3.40
## 6       2507        ohc           five        136       mpfi      3.19   3.40
##   compressionratio horsepower peakrpm citympg highwaympg price
## 1              9.0        111    5000      21         27 13495
## 2              9.0        111    5000      21         27 16500
## 3              9.0        154    5000      19         26 16500
## 4             10.0        102    5500      24         30 13950
## 5              8.0        115    5500      18         22 17450
## 6              8.5        110    5500      19         25 15250
names (data1)
##  [1] "car_ID"           "symboling"        "CarName"          "fueltype"        
##  [5] "aspiration"       "doornumber"       "carbody"          "drivewheel"      
##  [9] "enginelocation"   "wheelbase"        "carlength"        "carwidth"        
## [13] "carheight"        "curbweight"       "enginetype"       "cylindernumber"  
## [17] "enginesize"       "fuelsystem"       "boreratio"        "stroke"          
## [21] "compressionratio" "horsepower"       "peakrpm"          "citympg"         
## [25] "highwaympg"       "price"

Verifica que los datos se hayan cargado correctamente Data 2

head(data2) 
##            Make                           Model   Price Year Kilometer
## 1         Honda             Amaze 1.2 VX i-VTEC  505000 2017     87150
## 2 Maruti Suzuki                 Swift DZire VDI  450000 2014     75000
## 3       Hyundai            i10 Magna 1.2 Kappa2  220000 2011     67000
## 4        Toyota                        Glanza G  799000 2019     37500
## 5        Toyota Innova 2.4 VX 7 STR [2016-2020] 1950000 2018     69000
## 6 Maruti Suzuki                        Ciaz ZXi  675000 2017     73315
##   Fuel.Type Transmission  Location  Color  Owner Seller.Type  Engine
## 1    Petrol       Manual      Pune   Grey  First   Corporate 1198 cc
## 2    Diesel       Manual  Ludhiana  White Second  Individual 1248 cc
## 3    Petrol       Manual   Lucknow Maroon  First  Individual 1197 cc
## 4    Petrol       Manual Mangalore    Red  First  Individual 1197 cc
## 5    Diesel       Manual    Mumbai   Grey  First  Individual 2393 cc
## 6    Petrol       Manual      Pune   Grey  First  Individual 1373 cc
##            Max.Power             Max.Torque Drivetrain Length Width Height
## 1  87 bhp @ 6000 rpm      109 Nm @ 4500 rpm        FWD   3990  1680   1505
## 2  74 bhp @ 4000 rpm      190 Nm @ 2000 rpm        FWD   3995  1695   1555
## 3  79 bhp @ 6000 rpm 112.7619 Nm @ 4000 rpm        FWD   3585  1595   1550
## 4  82 bhp @ 6000 rpm      113 Nm @ 4200 rpm        FWD   3995  1745   1510
## 5 148 bhp @ 3400 rpm      343 Nm @ 1400 rpm        RWD   4735  1830   1795
## 6  91 bhp @ 6000 rpm      130 Nm @ 4000 rpm        FWD   4490  1730   1485
##   Seating.Capacity Fuel.Tank.Capacity
## 1                5                 35
## 2                5                 42
## 3                5                 35
## 4                5                 37
## 5                7                 55
## 6                5                 43
names(data2)
##  [1] "Make"               "Model"              "Price"             
##  [4] "Year"               "Kilometer"          "Fuel.Type"         
##  [7] "Transmission"       "Location"           "Color"             
## [10] "Owner"              "Seller.Type"        "Engine"            
## [13] "Max.Power"          "Max.Torque"         "Drivetrain"        
## [16] "Length"             "Width"              "Height"            
## [19] "Seating.Capacity"   "Fuel.Tank.Capacity"

Obtener un resumen de las variables Data 1

summary(data1)
##      car_ID      symboling         CarName            fueltype        
##  Min.   :  1   Min.   :-2.0000   Length:205         Length:205        
##  1st Qu.: 52   1st Qu.: 0.0000   Class :character   Class :character  
##  Median :103   Median : 1.0000   Mode  :character   Mode  :character  
##  Mean   :103   Mean   : 0.8341                                        
##  3rd Qu.:154   3rd Qu.: 2.0000                                        
##  Max.   :205   Max.   : 3.0000                                        
##   aspiration         doornumber          carbody           drivewheel       
##  Length:205         Length:205         Length:205         Length:205        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##                                                                             
##                                                                             
##                                                                             
##  enginelocation       wheelbase        carlength        carwidth    
##  Length:205         Min.   : 86.60   Min.   :141.1   Min.   :60.30  
##  Class :character   1st Qu.: 94.50   1st Qu.:166.3   1st Qu.:64.10  
##  Mode  :character   Median : 97.00   Median :173.2   Median :65.50  
##                     Mean   : 98.76   Mean   :174.0   Mean   :65.91  
##                     3rd Qu.:102.40   3rd Qu.:183.1   3rd Qu.:66.90  
##                     Max.   :120.90   Max.   :208.1   Max.   :72.30  
##    carheight       curbweight    enginetype        cylindernumber    
##  Min.   :47.80   Min.   :1488   Length:205         Length:205        
##  1st Qu.:52.00   1st Qu.:2145   Class :character   Class :character  
##  Median :54.10   Median :2414   Mode  :character   Mode  :character  
##  Mean   :53.72   Mean   :2556                                        
##  3rd Qu.:55.50   3rd Qu.:2935                                        
##  Max.   :59.80   Max.   :4066                                        
##    enginesize     fuelsystem          boreratio        stroke     
##  Min.   : 61.0   Length:205         Min.   :2.54   Min.   :2.070  
##  1st Qu.: 97.0   Class :character   1st Qu.:3.15   1st Qu.:3.110  
##  Median :120.0   Mode  :character   Median :3.31   Median :3.290  
##  Mean   :126.9                      Mean   :3.33   Mean   :3.255  
##  3rd Qu.:141.0                      3rd Qu.:3.58   3rd Qu.:3.410  
##  Max.   :326.0                      Max.   :3.94   Max.   :4.170  
##  compressionratio   horsepower       peakrpm        citympg     
##  Min.   : 7.00    Min.   : 48.0   Min.   :4150   Min.   :13.00  
##  1st Qu.: 8.60    1st Qu.: 70.0   1st Qu.:4800   1st Qu.:19.00  
##  Median : 9.00    Median : 95.0   Median :5200   Median :24.00  
##  Mean   :10.14    Mean   :104.1   Mean   :5125   Mean   :25.22  
##  3rd Qu.: 9.40    3rd Qu.:116.0   3rd Qu.:5500   3rd Qu.:30.00  
##  Max.   :23.00    Max.   :288.0   Max.   :6600   Max.   :49.00  
##    highwaympg        price      
##  Min.   :16.00   Min.   : 5118  
##  1st Qu.:25.00   1st Qu.: 7788  
##  Median :30.00   Median :10295  
##  Mean   :30.75   Mean   :13277  
##  3rd Qu.:34.00   3rd Qu.:16503  
##  Max.   :54.00   Max.   :45400

Obtener un resumen de las variables Data 2

summary(data2)
##      Make              Model               Price               Year     
##  Length:1874        Length:1874        Min.   :   49000   Min.   :1988  
##  Class :character   Class :character   1st Qu.:  500000   1st Qu.:2015  
##  Mode  :character   Mode  :character   Median :  842500   Median :2017  
##                                        Mean   : 1718279   Mean   :2017  
##                                        3rd Qu.: 1908250   3rd Qu.:2019  
##                                        Max.   :35000000   Max.   :2022  
##    Kilometer        Fuel.Type         Transmission         Location        
##  Min.   :      0   Length:1874        Length:1874        Length:1874       
##  1st Qu.:  28020   Class :character   Class :character   Class :character  
##  Median :  48798   Mode  :character   Mode  :character   Mode  :character  
##  Mean   :  53178                                                           
##  3rd Qu.:  71000                                                           
##  Max.   :2000000                                                           
##     Color              Owner           Seller.Type           Engine         
##  Length:1874        Length:1874        Length:1874        Length:1874       
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##                                                                             
##                                                                             
##                                                                             
##   Max.Power          Max.Torque         Drivetrain            Length    
##  Length:1874        Length:1874        Length:1874        Min.   :3099  
##  Class :character   Class :character   Class :character   1st Qu.:3985  
##  Mode  :character   Mode  :character   Mode  :character   Median :4360  
##                                                           Mean   :4282  
##                                                           3rd Qu.:4620  
##                                                           Max.   :5569  
##      Width          Height     Seating.Capacity Fuel.Tank.Capacity
##  Min.   :1475   Min.   :1213   Min.   :2.000    Min.   : 15.00    
##  1st Qu.:1695   1st Qu.:1485   1st Qu.:5.000    1st Qu.: 42.00    
##  Median :1770   Median :1544   Median :5.000    Median : 50.00    
##  Mean   :1768   Mean   :1589   Mean   :5.295    Mean   : 52.22    
##  3rd Qu.:1831   3rd Qu.:1671   3rd Qu.:5.000    3rd Qu.: 60.00    
##  Max.   :2220   Max.   :1995   Max.   :8.000    Max.   :105.00

Ver extructura de los datos Data 1

str(data1)
## 'data.frame':    205 obs. of  26 variables:
##  $ car_ID          : int  1 2 3 4 5 6 7 8 9 10 ...
##  $ symboling       : int  3 3 1 2 2 2 1 1 1 0 ...
##  $ CarName         : chr  "alfa-romero giulia" "alfa-romero stelvio" "alfa-romero Quadrifoglio" "audi 100 ls" ...
##  $ fueltype        : chr  "gas" "gas" "gas" "gas" ...
##  $ aspiration      : chr  "std" "std" "std" "std" ...
##  $ doornumber      : chr  "two" "two" "two" "four" ...
##  $ carbody         : chr  "convertible" "convertible" "hatchback" "sedan" ...
##  $ drivewheel      : chr  "rwd" "rwd" "rwd" "fwd" ...
##  $ enginelocation  : chr  "front" "front" "front" "front" ...
##  $ wheelbase       : num  88.6 88.6 94.5 99.8 99.4 ...
##  $ carlength       : num  169 169 171 177 177 ...
##  $ carwidth        : num  64.1 64.1 65.5 66.2 66.4 66.3 71.4 71.4 71.4 67.9 ...
##  $ carheight       : num  48.8 48.8 52.4 54.3 54.3 53.1 55.7 55.7 55.9 52 ...
##  $ curbweight      : int  2548 2548 2823 2337 2824 2507 2844 2954 3086 3053 ...
##  $ enginetype      : chr  "dohc" "dohc" "ohcv" "ohc" ...
##  $ cylindernumber  : chr  "four" "four" "six" "four" ...
##  $ enginesize      : int  130 130 152 109 136 136 136 136 131 131 ...
##  $ fuelsystem      : chr  "mpfi" "mpfi" "mpfi" "mpfi" ...
##  $ boreratio       : num  3.47 3.47 2.68 3.19 3.19 3.19 3.19 3.19 3.13 3.13 ...
##  $ stroke          : num  2.68 2.68 3.47 3.4 3.4 3.4 3.4 3.4 3.4 3.4 ...
##  $ compressionratio: num  9 9 9 10 8 8.5 8.5 8.5 8.3 7 ...
##  $ horsepower      : int  111 111 154 102 115 110 110 110 140 160 ...
##  $ peakrpm         : int  5000 5000 5000 5500 5500 5500 5500 5500 5500 5500 ...
##  $ citympg         : int  21 21 19 24 18 19 19 19 17 16 ...
##  $ highwaympg      : int  27 27 26 30 22 25 25 25 20 22 ...
##  $ price           : num  13495 16500 16500 13950 17450 ...

Ver extructura de los datos Data 2

str(data2)
## 'data.frame':    1874 obs. of  20 variables:
##  $ Make              : chr  "Honda" "Maruti Suzuki" "Hyundai" "Toyota" ...
##  $ Model             : chr  "Amaze 1.2 VX i-VTEC" "Swift DZire VDI" "i10 Magna 1.2 Kappa2" "Glanza G" ...
##  $ Price             : int  505000 450000 220000 799000 1950000 675000 2650000 1390000 575000 591000 ...
##  $ Year              : int  2017 2014 2011 2019 2018 2017 2017 2017 2015 2017 ...
##  $ Kilometer         : int  87150 75000 67000 37500 69000 73315 75000 56000 85000 20281 ...
##  $ Fuel.Type         : chr  "Petrol" "Diesel" "Petrol" "Petrol" ...
##  $ Transmission      : chr  "Manual" "Manual" "Manual" "Manual" ...
##  $ Location          : chr  "Pune" "Ludhiana" "Lucknow" "Mangalore" ...
##  $ Color             : chr  "Grey" "White" "Maroon" "Red" ...
##  $ Owner             : chr  "First" "Second" "First" "First" ...
##  $ Seller.Type       : chr  "Corporate" "Individual" "Individual" "Individual" ...
##  $ Engine            : chr  "1198 cc" "1248 cc" "1197 cc" "1197 cc" ...
##  $ Max.Power         : chr  "87 bhp @ 6000 rpm" "74 bhp @ 4000 rpm" "79 bhp @ 6000 rpm" "82 bhp @ 6000 rpm" ...
##  $ Max.Torque        : chr  "109 Nm @ 4500 rpm" "190 Nm @ 2000 rpm" "112.7619 Nm @ 4000 rpm" "113 Nm @ 4200 rpm" ...
##  $ Drivetrain        : chr  "FWD" "FWD" "FWD" "FWD" ...
##  $ Length            : int  3990 3995 3585 3995 4735 4490 4439 4670 4331 3985 ...
##  $ Width             : int  1680 1695 1595 1745 1830 1730 1821 1814 1822 1734 ...
##  $ Height            : int  1505 1555 1550 1510 1795 1485 1612 1476 1671 1505 ...
##  $ Seating.Capacity  : int  5 5 5 5 7 5 5 5 5 5 ...
##  $ Fuel.Tank.Capacity: num  35 42 35 37 55 43 51 50 50 45 ...

Primera seccion del primer Dataset

Descripción de cada variable

  1. Car_ID: Código único que identifica cada registro.
  2. Symboling: Categoría de riesgo de seguro asignada al vehículo.
  3. carCompany: Marca o fabricante del automóvil.
  4. fueltype: Tipo de combustible usado por el coche, como gasolina o diésel.
  5. aspiration: Método de aspiración del motor, como estándar o turbo.
  6. doornumber: Cantidad de puertas que tiene el vehículo.
  7. carbody: Tipo de carrocería del vehículo, como sedán, hatchback, etc.
  8. drivewheel: Tipo de tracción del automóvil, por ejemplo, tracción delantera o trasera.
  9. enginelocation: Posición del motor en el vehículo, ya sea en la parte delantera o trasera.
  10. wheelbase: Longitud entre los ejes delantero y trasero del automóvil.
  11. carlength: Largo total del vehículo.
  12. carwidth: Ancho total del vehículo.
  13. carheight: Altura total del vehículo.
  14. curbweight: Peso del coche vacío, sin pasajeros ni carga.
  15. enginetype: Tipo de motor, como DOHC, OHV, etc.
  16. cylindernumber: Número de cilindros en el motor.
  17. enginesize: Tamaño del motor en centímetros cúbicos.
  18. fuelsystem: Sistema de inyección de combustible del automóvil, como inyección directa o carburador.
  19. boreratio: Relación entre el diámetro y la carrera del cilindro.
  20. stroke: Distancia que recorre el pistón en el cilindro.
  21. compressionratio: Tasa de compresión del motor del coche.
  22. horsepower: Potencia del motor medida en caballos de fuerza.
  23. peakrpm: Máxima cantidad de revoluciones por minuto del motor.
  24. citympg: Eficiencia de combustible en millas por galón en áreas urbanas.
  25. highwaympg: Eficiencia de combustible en millas por galón en carreteras.
  26. price: Precio del vehículo, la variable de interés en este análisis.

Revision de dataset 1

Después de revisar el dataset y explorarlo, ahora tengo los detalles necesarios para eliminar las variables cualitativas, lo que permitirá centrar el análisis de correlación solo con las variables numéricas.

Ver extructura de los datos Data 2

str(data2)
## 'data.frame':    1874 obs. of  20 variables:
##  $ Make              : chr  "Honda" "Maruti Suzuki" "Hyundai" "Toyota" ...
##  $ Model             : chr  "Amaze 1.2 VX i-VTEC" "Swift DZire VDI" "i10 Magna 1.2 Kappa2" "Glanza G" ...
##  $ Price             : int  505000 450000 220000 799000 1950000 675000 2650000 1390000 575000 591000 ...
##  $ Year              : int  2017 2014 2011 2019 2018 2017 2017 2017 2015 2017 ...
##  $ Kilometer         : int  87150 75000 67000 37500 69000 73315 75000 56000 85000 20281 ...
##  $ Fuel.Type         : chr  "Petrol" "Diesel" "Petrol" "Petrol" ...
##  $ Transmission      : chr  "Manual" "Manual" "Manual" "Manual" ...
##  $ Location          : chr  "Pune" "Ludhiana" "Lucknow" "Mangalore" ...
##  $ Color             : chr  "Grey" "White" "Maroon" "Red" ...
##  $ Owner             : chr  "First" "Second" "First" "First" ...
##  $ Seller.Type       : chr  "Corporate" "Individual" "Individual" "Individual" ...
##  $ Engine            : chr  "1198 cc" "1248 cc" "1197 cc" "1197 cc" ...
##  $ Max.Power         : chr  "87 bhp @ 6000 rpm" "74 bhp @ 4000 rpm" "79 bhp @ 6000 rpm" "82 bhp @ 6000 rpm" ...
##  $ Max.Torque        : chr  "109 Nm @ 4500 rpm" "190 Nm @ 2000 rpm" "112.7619 Nm @ 4000 rpm" "113 Nm @ 4200 rpm" ...
##  $ Drivetrain        : chr  "FWD" "FWD" "FWD" "FWD" ...
##  $ Length            : int  3990 3995 3585 3995 4735 4490 4439 4670 4331 3985 ...
##  $ Width             : int  1680 1695 1595 1745 1830 1730 1821 1814 1822 1734 ...
##  $ Height            : int  1505 1555 1550 1510 1795 1485 1612 1476 1671 1505 ...
##  $ Seating.Capacity  : int  5 5 5 5 7 5 5 5 5 5 ...
##  $ Fuel.Tank.Capacity: num  35 42 35 37 55 43 51 50 50 45 ...
# Cargar librerias (dplyr)

library(highcharter)
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(corrplot)
## corrplot 0.92 loaded
library(mod)
## 
## Attaching package: 'mod'
## The following objects are masked from 'package:base':
## 
##     drop, use
library(FactoMineR)
library(openxlsx)

Variables cuantitativas del primer dataset

cuantitativas <- c( "price", "wheelbase", "carlength", "carwidth", "carheight",
                    "curbweight", "enginesize", "boreratio", "stroke",
                    "compressionratio", "horsepower", "peakrpm", "citympg",
                    "highwaympg") 
subset1 <- data1[, cuantitativas] 

head(subset1)
##   price wheelbase carlength carwidth carheight curbweight enginesize boreratio
## 1 13495      88.6     168.8     64.1      48.8       2548        130      3.47
## 2 16500      88.6     168.8     64.1      48.8       2548        130      3.47
## 3 16500      94.5     171.2     65.5      52.4       2823        152      2.68
## 4 13950      99.8     176.6     66.2      54.3       2337        109      3.19
## 5 17450      99.4     176.6     66.4      54.3       2824        136      3.19
## 6 15250      99.8     177.3     66.3      53.1       2507        136      3.19
##   stroke compressionratio horsepower peakrpm citympg highwaympg
## 1   2.68              9.0        111    5000      21         27
## 2   2.68              9.0        111    5000      21         27
## 3   3.47              9.0        154    5000      19         26
## 4   3.40             10.0        102    5500      24         30
## 5   3.40              8.0        115    5500      18         22
## 6   3.40              8.5        110    5500      19         25

Matriz de correlacion para todas las variables

par(oma = c(1, 1, 1, 1), mar = c(5, 4, 4, 2) + 0.1)

corrplot.mixed(cor(subset1),
               lower = "circle", 
               upper = "circle",
               tl.pos = "n")
corrplot(cor(subset1), add = TRUE, method = "circle", 
         type = "upper", tl.pos = "lt", # Etiquetas en la parte superior izquierda
         tl.col = "black", number.cex = 0.7, addCoef.col = "black",
         cl.pos = "n", 
         diag = TRUE)

Variables Cualitativas

Al momento de filtrar las variables cualitativas, se paso a filtrarlas y el siguiente paso seria elegir las variables que tengan mejor correlacion con la variable dependiente que es el “precio” , los cuales podemos observar de acuerdo a la grafica anterior y escogiendo todas las variables con una correlacion mayor a 0.5 y menor a - 0.5

Matriz de correlaciones con variables ente corr mayor a 0.5 y menor a - 0.5

subset_precio <- subset1[, c("price","curbweight","enginesize","boreratio",
                             "horsepower","wheelbase","carlength","carwidth",
                              "citympg","highwaympg")]

par(oma = c(1, 1, 1, 1), mar = c(5, 4, 4, 2) + 0.1)

corrplot.mixed(cor(subset_precio),
               lower = "circle", 
               upper = "circle",
               tl.pos = "n")
corrplot(cor(subset_precio), add = TRUE, method = "circle", 
         type = "upper", tl.pos = "lt", # Etiquetas en la parte superior izquierda
         tl.col = "black", number.cex = 0.7, addCoef.col = "black",
         cl.pos = "n", 
         diag = TRUE)

# Hipótesis del Modelo del primer dataset 1

Hipótesis Global (Prueba F)

La hipótesis nula (\(H_0\)) y la hipótesis alternativa (\(H_1\)) para la prueba F son:

\[ H_0: \beta_1 = \beta_2 = \beta_3 = \dots = \beta_k = 0 \]

\[ H_1: \text{por lo menos uno de los coeficientes } \beta_i \text{ es diferente de cero} \]

En donde \(\beta_i\) son los coeficientes de las variables independientes en el modelo.

Hipótesis Individual (Prueba t-Student)

Para cada una de las variables independiente en el modelo, la hipótesis nula (\(H_0\)) y la hipótesis alternativa (\(H_1\)) son:

\[ H_0: \beta_i = 0 \]

\[ H_1: \beta_i \neq 0 \]

Estas hipótesis se verifican de manera individual para cada \(\beta_i\) empleando la prueba t de Student. En este caso, \(\beta_i\) corresponde al coeficiente asociado a la variable independiente \(x_i\) dentro del modelo de regresión. # Ajustar el modelo de regresión múltiple con las variables más correlacionadas del primer dataset

model1 <- lm(price ~ curbweight + enginesize + boreratio + horsepower + wheelbase + 
             carlength + carwidth + citympg + highwaympg, data = subset_precio)

summary(model1)
## 
## Call:
## lm(formula = price ~ curbweight + enginesize + boreratio + horsepower + 
##     wheelbase + carlength + carwidth + citympg + highwaympg, 
##     data = subset_precio)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
##  -8297  -1542     31   1307  14444 
## 
## Coefficients:
##               Estimate Std. Error t value Pr(>|t|)    
## (Intercept) -43223.926  13760.207  -3.141 0.001944 ** 
## curbweight       2.918      1.651   1.767 0.078749 .  
## enginesize      83.615     13.434   6.224 2.91e-09 ***
## boreratio    -1140.464   1212.508  -0.941 0.348083    
## horsepower      53.754     15.447   3.480 0.000619 ***
## wheelbase      109.895    101.743   1.080 0.281418    
## carlength      -57.853     57.933  -0.999 0.319217    
## carwidth       532.467    255.561   2.084 0.038508 *  
## citympg       -119.815    185.536  -0.646 0.519183    
## highwaympg     122.855    170.820   0.719 0.472872    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 3444 on 195 degrees of freedom
## Multiple R-squared:  0.8223, Adjusted R-squared:  0.8141 
## F-statistic: 100.3 on 9 and 195 DF,  p-value: < 2.2e-16

Variables eliminadas de las mas corrlacionadas

Las variables boreratio, wheelbase, carlength, citympg y highwaympg fueron eliminadas, ya que sus valores p superan el 0.05, lo que significa que no son relevantes desde el punto de vista estadístico para predecir el precio del automóvil. Las variables que permanecen en el modelo son aquellas que presentan una significancia estadística notable y un impacto positivo considerable en el precio, como enginesize, horsepower y carwidth.

Variables con mayor significancia

subset_precio2 <- subset_precio[, c("price", "enginesize", "horsepower", 
                             "carwidth")]
modelo2 <- lm(price ~  enginesize  + horsepower 
             + carwidth , data = subset_precio2)
summary(modelo2)
## 
## Call:
## lm(formula = price ~ enginesize + horsepower + carwidth, data = subset_precio2)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -8497.8 -1920.2   -73.5  1356.2 14441.1 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept) -60205.61   10223.64  -5.889 1.61e-08 ***
## enginesize      94.94      11.26   8.436 6.41e-15 ***
## horsepower      52.80      10.46   5.048 9.98e-07 ***
## carwidth       848.70     166.97   5.083 8.48e-07 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 3444 on 201 degrees of freedom
## Multiple R-squared:  0.8169, Adjusted R-squared:  0.8141 
## F-statistic: 298.9 on 3 and 201 DF,  p-value: < 2.2e-16

Ecuacion del modelo

\[\text{Price} = −60205.61 + (94.94 \times \text{Enginesize}) + (52.80 \times \text{Horsepower}) + (848.70 \times \text{Carwidth}) )\] # Caso de estudio del primer dataset Una compañía reconocida de automóviles (Great Wall Motors) de la República Popular de China aspira entrar en el mercado americano estableciendo allí sus centros de fabricación y ensamblaje de automóviles para competir localmente con sus contrapartes americanas o europeas.

Dicha compañía ha contratado un grupo de consultores denominados “Los científicos de datos” para obtener un modelo predictivo que explique el precio de los automóviles. Específicamente, quieren comprender las variables que explican (estadísticamente) el precio de los automóviles en el mercado americano, ya que pueden ser muy diferentes del mercado chino. La empresa quiere responderse lo siguiente:

  1. ¿Qué variables son significativas para predecir el precio de un automóvil? Sustente su respuesta con los resultados que obtuvo.

Las variables enginesize, horsepower y carwidth juegan un papel importante en la predicción del precio de un automóvil. Esto se deduce a partir de los valores p obtenidos en el modelo:

Enginesize: p-valor = 6.41×10−15 (extremadamente significativo, p < 0.001). Horsepower: p-valor = 9.98×10−7 (extremadamente significativo, p < 0.001). Carwidth: p-valor = 8.48×10−7 (extremadamente significativo, p < 0.001).

Como los valores p son todos menores a 0.05, esto indica que existe una relación significativa entre estas variables y el precio del vehículo. Por lo tanto, cualquier variación en ellas influye directamente en el precio del automóvil.

  1. ¿Qué tan bien esas variables explican el precio de un automóvil? Sustente su respuesta con los resultados que obtuvo.

El R-cuadrado del modelo es 0.8169, lo que significa que alrededor del 81.69% de la variabilidad en el precio del automóvil se explica por las variables enginesize, horsepower y carwidth. Esto sugiere que el modelo es eficaz para predecir el precio, ya que un R-cuadrado superior a 0.80 indica un buen ajuste.

Es importante asegurarse de que los datos no estén sesgados ni tengan valores atípicos, ya que podrían inflar el R-cuadrado y afectar la precisión del modelo.

Segunda seccion del dataset #2

Descripción de las variables

Make: Fabricante del automóvil. Model: Versión específica del vehículo. Price: Valor del automóvil en la moneda local. Year: Año en que se fabricó el automóvil. Kilometer: Distancia recorrida por el automóvil. Fuel.Type: Tipo de combustible que usa el vehículo (por ejemplo, gasolina o diésel). Transmission: Tipo de transmisión del automóvil, ya sea manual o automática. Location: Lugar donde está ubicado el automóvil. Color: Tono exterior del vehículo. Owner: Cantidad de dueños previos del automóvil. Seller.Type: Tipo de vendedor, ya sea un concesionario o un particular. Engine: Especificaciones del motor del automóvil. Max.Power: Potencia máxima que puede generar el motor. Max.Torque: Máximo torque que puede producir el motor. Drivetrain: Sistema de tracción del automóvil (delantera, total, etc.). Length: Longitud del automóvil en milímetros. Width: Ancho del automóvil en milímetros. Height: Altura del automóvil en milímetros. Seating.Capacity: Número de pasajeros que pueden viajar en el automóvil. Fuel.Tank.Capacity: Capacidad del tanque de combustible en litros.

Revision de dataset 2

Luego de revisar ambos conjuntos de datos, vamos a realizar una selección de las variables necesarias. Para el análisis de regresión múltiple y la construcción del modelo para la variable dependiente, solo incluiremos las variables numéricas.

Variables cuantitativas del segundo dataset

cuantitativas2 <- c("Price", "Kilometer", "Length", "Width", "Height", "Seating.Capacity", "Fuel.Tank.Capacity")
subset2 <- data2[, cuantitativas2]

head(subset2)
##     Price Kilometer Length Width Height Seating.Capacity Fuel.Tank.Capacity
## 1  505000     87150   3990  1680   1505                5                 35
## 2  450000     75000   3995  1695   1555                5                 42
## 3  220000     67000   3585  1595   1550                5                 35
## 4  799000     37500   3995  1745   1510                5                 37
## 5 1950000     69000   4735  1830   1795                7                 55
## 6  675000     73315   4490  1730   1485                5                 43

Matriz de correlacion con todas las varibles

par(oma = c(1, 1, 1, 1), mar = c(5, 4, 4, 2) + 0.1)

corrplot.mixed(cor(subset2),
               lower = "number", 
               upper = "circle",
               tl.pos = "n")
corrplot(cor(subset2), add = TRUE, method = "circle", 
         type = "upper", tl.pos = "lt", # Etiquetas en la parte superior izquierda
         tl.col = "black", number.cex = 0.7, addCoef.col = "black",
         cl.pos = "n",
         diag = TRUE)

## Variables Cuantitavas

Despues de revisar las varibles cuantitativas, el siguiente paso seria seleccionar las variables cualitativas que mejor se relacionan con la variable dependiente, en este caso, el precio. Para ello, podemos revisar la gráfica anterior y optar por aquellas variables cuya correlación sea superior a 0.5 o inferior a -0.5.

Matriz de correlaciones con variables entre correlaciones de 0.5 y menor a - 0.5

subset2_price <- subset2[, c("Price", "Length","Width","Fuel.Tank.Capacity")]


par(oma = c(1, 1, 1, 1), mar = c(5, 4, 4, 2) + 0.1)

corrplot.mixed(cor(subset2_price),
               lower = "number", 
               upper = "circle",
               tl.pos = "n")
corrplot(cor(subset2_price), add = TRUE, method = "circle", 
         type = "upper", tl.pos = "lt", # Etiquetas en la parte superior izquierda
         tl.col = "black", number.cex = 0.7, addCoef.col = "black",
         cl.pos = "n",
         diag = TRUE)

# Ajustar el modelo de regresión múltiple con las variables más correlacionadas del segundo dataset

modelo2 <- lm(Price ~ Length + Width + Fuel.Tank.Capacity, data = subset2_price)
summary(modelo2)
## 
## Call:
## lm(formula = Price ~ Length + Width + Fuel.Tank.Capacity, data = subset2_price)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -4226517  -778163  -216094   412501 31125964 
## 
## Coefficients:
##                      Estimate Std. Error t value Pr(>|t|)    
## (Intercept)        -1.210e+07  8.158e+05 -14.838  < 2e-16 ***
## Length              9.343e+02  1.909e+02   4.894 1.07e-06 ***
## Width               4.300e+03  6.084e+02   7.068 2.22e-12 ***
## Fuel.Tank.Capacity  4.252e+04  5.421e+03   7.844 7.30e-15 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1903000 on 1870 degrees of freedom
## Multiple R-squared:  0.3857, Adjusted R-squared:  0.3847 
## F-statistic: 391.4 on 3 and 1870 DF,  p-value: < 2.2e-16

Ecuacion del modelo

\[ \text{Price} = -1.210 \times 10^7 + (9.343 \times 10^2 \times \text{Length}) + (4.300 \times 10^3 \times \text{Width}) + (4.252 \times 10^4 \times \text{Fuel.Tank.Capacity)} \]

Caso de estudio del segundo dataset

Se ha contratado a un informático para que haga un estudio de autos usados para una microempresa que desea iniciar en ese tipo de negocio. Lo primero que se le pide es que obtenga los datos que la mencionada empresa no dispone. Luego se le pide que analice los datos para conocer cuáles son aquellas características de los autos de las que depende el precio de los autos para según eso adquirir autos usados basados en esas características. El informático obtuvo los datos haciendo webscrpaing y los recopiló en el dataset denominado UsedCars.csv. Ahora necesita de un científico de datos que le ayude a responder lo siguiente:

  1. ¿Qué variables son significativas para explicar el precio de un automóvil? Sustente su respuesta con los resultados que obtuvo.

En la tabla de coeficientes se muestran los valores p (Pr(>|t|)) para cada variable, los cuales indican la relevancia estadística de cada una dentro del modelo. Generalmente, una variable se considera significativa si su valor p es menor a un valor de referencia comúnmente aceptado, como 0.05.

Intercepto: Pr(>|t|) < 2×10−16, lo que indica una gran significancia. Length: Pr(>|t|) = 1.07×10−6, siendo menor a 0.05, es significativo. Width: Pr(>|t|) = 2.22×10−12, al ser menor que 0.05, también es significativo. Fuel.Tank.Capacity: Pr(>|t|) = 7.30×10−15, nuevamente menor a 0.05, lo que lo hace significativo.

En resumen, todas las variables incluidas en el modelo, como Length, Width y Fuel.Tank.Capacity, resultan ser estadísticamente significativas para predecir el precio del automóvil, dado que sus valores p son considerablemente inferiores a 0.05.

  1. ¿Qué tan bien esas variables explican el precio de un automóvil? Sustente su respuesta con los resultados que obtuvo.

El R-cuadrado representa la proporción de la variación en el precio que es explicada por las variables incluidas en el modelo. En este caso, un R-cuadrado de 0.3857 indica que aproximadamente el 38.57% de la variación en el precio del automóvil puede atribuirse a las variables Length, Width y Fuel.Tank.Capacity.

El R-cuadrado ajustado, que considera el número de variables en el modelo, es ligeramente inferior, con un valor de 0.3847. Este ajuste es útil cuando se comparan modelos con diferentes cantidades de variables.