Ejemplo 1

Un artículo en el Journal of Sound and Vibration (Vol. 151, 1991, pp. 383-394) describe un estudio que investiga la relación entre la exposición al ruido y la hipertensión. Los siguientes datos son representativos de los reportados en el artículo.

x<-c(60,  63,  65,  70,  70,  70,  80,  90,  80,  80,  85,  89,  90,  90,  90,  90,  94, 100, 100, 100)
y<-c(1, 0, 1, 2, 5, 1, 4, 6, 2, 3, 5, 4, 6, 8, 4 ,5, 7, 9, 7, 6)
hiper<-cbind(x,y)
hiper<-as.data.frame(hiper)
library(dplyr)
## Warning: replacing previous import 'lifecycle::last_warnings' by
## 'rlang::last_warnings' when loading 'pillar'
hiper%>%DT::datatable()

Aquí, la variable \(y\) representa el aumento de la presión arterial en milímetros de mercurio y la variable \(x\) representa el nivel de presión acústica en decibeles.

plot(x,y)

correlación

cor(x,y)
## [1] 0.8650185

usando ggplot

library(ggplot2)
ggplot(hiper, aes(x=x, y=y))+
  geom_point(col="blue")

modelo<-lm(y~x)
summary(modelo)
## 
## Call:
## lm(formula = y ~ x)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -1.8120 -0.9040 -0.1333  0.5023  2.9310 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept) -10.13154    1.99490  -5.079 7.83e-05 ***
## x             0.17429    0.02383   7.314 8.57e-07 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1.318 on 18 degrees of freedom
## Multiple R-squared:  0.7483, Adjusted R-squared:  0.7343 
## F-statistic:  53.5 on 1 and 18 DF,  p-value: 8.567e-07

la ecuación de la recta es:

\[\hat{y}=-10.13154+ 0.17429x\]

ggplot(hiper, aes(x=x,y=y))+
  geom_point(col="red")+
  geom_smooth(method = lm, se=F)

Ejemplo 2

library(GGally)
library(MASS)
library(ISLR)
data("Boston")
Boston%>%DT::datatable()
dim(Boston)
## [1] 506  14
colnames(Boston)
##  [1] "crim"    "zn"      "indus"   "chas"    "nox"     "rm"      "age"    
##  [8] "dis"     "rad"     "tax"     "ptratio" "black"   "lstat"   "medv"
str(Boston)
## 'data.frame':    506 obs. of  14 variables:
##  $ crim   : num  0.00632 0.02731 0.02729 0.03237 0.06905 ...
##  $ zn     : num  18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
##  $ indus  : num  2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
##  $ chas   : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ nox    : num  0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
##  $ rm     : num  6.58 6.42 7.18 7 7.15 ...
##  $ age    : num  65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
##  $ dis    : num  4.09 4.97 4.97 6.06 6.06 ...
##  $ rad    : int  1 2 2 3 3 3 5 5 5 5 ...
##  $ tax    : num  296 242 242 222 222 222 311 311 311 311 ...
##  $ ptratio: num  15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
##  $ black  : num  397 397 393 395 397 ...
##  $ lstat  : num  4.98 9.14 4.03 2.94 5.33 ...
##  $ medv   : num  24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...

El dataset Boston del paquete MASS recoge la mediana del valor de la vivienda en 506 Ɣreas residenciales de Boston. Junto con el precio, se han registrado 13 variables adicionales.

library(psych)

La variable chas es una variable categórica por lo que se transforma a factor

Boston$chas <- as.factor(Boston$chas)
summary(Boston)
##       crim                zn             indus       chas         nox        
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   0:471   Min.   :0.3850  
##  1st Qu.: 0.08205   1st Qu.:  0.00   1st Qu.: 5.19   1: 35   1st Qu.:0.4490  
##  Median : 0.25651   Median :  0.00   Median : 9.69           Median :0.5380  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14           Mean   :0.5547  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10           3rd Qu.:0.6240  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74           Max.   :0.8710  
##        rm             age              dis              rad        
##  Min.   :3.561   Min.   :  2.90   Min.   : 1.130   Min.   : 1.000  
##  1st Qu.:5.886   1st Qu.: 45.02   1st Qu.: 2.100   1st Qu.: 4.000  
##  Median :6.208   Median : 77.50   Median : 3.207   Median : 5.000  
##  Mean   :6.285   Mean   : 68.57   Mean   : 3.795   Mean   : 9.549  
##  3rd Qu.:6.623   3rd Qu.: 94.08   3rd Qu.: 5.188   3rd Qu.:24.000  
##  Max.   :8.780   Max.   :100.00   Max.   :12.127   Max.   :24.000  
##       tax           ptratio          black            lstat      
##  Min.   :187.0   Min.   :12.60   Min.   :  0.32   Min.   : 1.73  
##  1st Qu.:279.0   1st Qu.:17.40   1st Qu.:375.38   1st Qu.: 6.95  
##  Median :330.0   Median :19.05   Median :391.44   Median :11.36  
##  Mean   :408.2   Mean   :18.46   Mean   :356.67   Mean   :12.65  
##  3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:396.23   3rd Qu.:16.95  
##  Max.   :711.0   Max.   :22.00   Max.   :396.90   Max.   :37.97  
##       medv      
##  Min.   : 5.00  
##  1st Qu.:17.02  
##  Median :21.20  
##  Mean   :22.53  
##  3rd Qu.:25.00  
##  Max.   :50.00
ggpairs(Boston[,1:3], aes(colour=Boston$chas))

ggpairs(Boston[,5:9], aes(colour=Boston$chas))

ggpairs(Boston[,10:14], aes(colour=Boston$chas))

Se pretende predecir el valor de la vivienda en función del porcentaje de pobreza de la población.

modelo1<- lm(data = Boston, formula = medv ~ lstat)

La función lm() genera un objeto que almacena toda la información del modelo, para ver su contenido se emplea la función names() y para visualizar los principales parÔmetros del modelo generado se utiliza summary().

names(modelo1)
##  [1] "coefficients"  "residuals"     "effects"       "rank"         
##  [5] "fitted.values" "assign"        "qr"            "df.residual"  
##  [9] "xlevels"       "call"          "terms"         "model"
summary(modelo1)
## 
## Call:
## lm(formula = medv ~ lstat, data = Boston)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -15.168  -3.990  -1.318   2.034  24.500 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 34.55384    0.56263   61.41   <2e-16 ***
## lstat       -0.95005    0.03873  -24.53   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 6.216 on 504 degrees of freedom
## Multiple R-squared:  0.5441, Adjusted R-squared:  0.5432 
## F-statistic: 601.6 on 1 and 504 DF,  p-value: < 2.2e-16

-Residual standar error (RSE): En promedio, cualquier predicción del modelo se aleja 6.216 unidades del verdadero valor.

confint(modelo1, level = 0.95)
##                 2.5 %     97.5 %
## (Intercept) 33.448457 35.6592247
## lstat       -1.026148 -0.8739505
ggplot(Boston, aes(x=lstat, y=medv))+
  geom_point(color="red")+
  geom_smooth(method ="lm" , se=FALSE)
## `geom_smooth()` using formula 'y ~ x'

library(plotly)
a<-ggplot(Boston, aes(x=lstat, y=medv))+
  geom_point(color="red")+
  geom_smooth(method ="lm" , se=FALSE)
ggplotly(a)

\(precio \ medio \ vivienda = 34.55 -0.95\cdot lstat\)