R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

edad <- c(20, 21, 22, 23, 24, 25, 26, 27) #vector edad
mean(edad) #media de la variable edad
## [1] 23.5
## [1] 23.5
median(edad) #mediana de la variable edad
## [1] 23.5
## [1] 23.5
var(edad) #varianza de la variable edad
## [1] 6
## [1] 6
sd(edad) #desviación típica de la variable edad
## [1] 2.44949
## [1] 2.44949
min(edad) #valor mínimo de la variable edad
## [1] 20
## [1] 20
max(edad) #valor máximo de la variable edad
## [1] 27
## [1] 27
range(edad) #valores mín. y máx. de la variable edad 
## [1] 20 27
## [1] 20 27
#sapply interesante para resumen de valores estadisticos
sapply(iris, mean, na.rm=TRUE) #de esta forma no tenemos en cuenta los missings o valores faltantes
## Warning in mean.default(X[[i]], ...): argument is not numeric or logical:
## returning NA
## Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species 
##     5.843333     3.057333     3.758000     1.199333           NA
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species 
## 5.843333 3.057333 3.758000 1.199333 NA
#Ejemplo 2
#definición de las variables en vectores
id=c(100,110,120,130,140,150,160,170,180,190)
edad=c(18,19,NA,18,24,27,22,25,22,15)
gen=c(2,1,2,2,1,2,1,1,2,1)
peso=c(65,58,56,61,84,99,50,64,87,87)
altura=c(161,170,174,165,150,171,181,170,184,190)
niv_col=c(1,2,3,1,3,2,3,1,2,3)
#usaremos diferentes comandos estadísticos en diferentes variables
sort(edad) #ordenamos la variable edad
## [1] 15 18 18 19 22 22 24 25 27
## [1] 15 18 18 19 22 22 24 25 27
summary(edad) #buscamos un resumen estadístico básico de la variable edad
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##   15.00   18.00   22.00   21.11   24.00   27.00       1
## Min. 1st Qu. Median Mean 3rd Qu. Max. NA's 
## 15.00 18.00 22.00 21.11 24.00 27.00 1
fivenum(gen) #buscamos los cinco estadísticos descriptivos básicos
## [1] 1.0 1.0 1.5 2.0 2.0
## [1] 1.0 1.0 1.5 2.0 2.0
mean(peso) #media de la variable peso
## [1] 71.1
## [1] 71.1
median(altura) #mediana de la variable altura
## [1] 170.5
## [1] 170.5
var(altura) #varianza de la variable altura
## [1] 134.9333
## [1] 134.9333
cor(altura, peso) #correlación de las variables altura y peso
## [1] 0.07103622
## [1] 0.07103622
sd(altura) #desviación típica de altura
## [1] 11.61608
## [1] 11.61608
#ejemplo 3
gen2=factor(gen, levels=c(1,2), labels=c("Hombre","Mujer")) #generamos un factor con sus nuevas etiquetas
niv_col2=factor(niv_col, levels=c(1,2,3), labels=c("Colesterol Bajo",
"Colesterol Normal","Colesterol Alto"))
#Ejemplo 4
#Para   mostrar cómo    podemos recodificar variables,  vamos   a   ver un  ejemplo nuevo:  
Ident <- 1:5;
Genero <- c("Masculino", "Femenino", "Masculino", "Masculino", "Femenino") 
Salud <- c(0, 1, 1, 0, 1) #donde 0 es sano y 1 enfermo
Opinion <- c("Mucho", "Poco", "Mucho", "Bastante", "Mucho")
Fuma <- c("1", "2", "1", "2", "2")
Opin_Pacientes <- data.frame(Ident, Genero, Salud, Opinion, Fuma) 
Opin_Pacientes
##   Ident    Genero Salud  Opinion Fuma
## 1     1 Masculino     0    Mucho    1
## 2     2  Femenino     1     Poco    2
## 3     3 Masculino     1    Mucho    1
## 4     4 Masculino     0 Bastante    2
## 5     5  Femenino     1    Mucho    2
## Ident Género Salud Opinión Fuma
## 1 1 Masculino 0 Mucho 1
## 2 2 Femenino 1 Poco 2
## 3 3 Masculino 1 Mucho 1
## 4 4 Masculino 0 Bastante 2
## 5 5 Femenino 1 Mucho 2
#En primer  lugar,  queremos    cambiar los valores de  la  variable    Salud,  ya  que incluir un  0   puede   
#ocasionar  problemas   de  análisis    posteriores.    Cambiamos   los valores a   1   y   2:  
Opin_Pacientes[Opin_Pacientes$Salud==0] <- 1
Opin_Pacientes[Opin_Pacientes$Salud==0] <- 2
Opin_Pacientes
##   Ident    Genero Salud Opinion Fuma
## 1     2 Masculino     0       2    1
## 2     2  Femenino     1       2    2
## 3     2 Masculino     1       2    1
## 4     2 Masculino     0       2    2
## 5     2  Femenino     1       2    2
## Ident Género Salud Opinión Fuma
## 1 2 Masculino 0 2 1
## 2 2 Femenino 1 2 2
## 3 2 Masculino 1 2 1
## 4 2 Masculino 0 2 2
## 5 2 Femenino 1 2 2
#En segundo lugar,  nos gustaría    recodificar la  variable    Salud del   conjunto    de  datos   inicial (con    
#valores    1,  0)  a   un  factor  con Sano    y   Enfermo:    
reco1 <- Opin_Pacientes
reco1$Salud <- factor(reco1$Salud)
levels(reco1$Salud)[1] <- "Sano"
levels(reco1$Salud)[1] <- "Enfermo"
reco1
##   Ident    Genero   Salud Opinion Fuma
## 1     2 Masculino Enfermo       2    1
## 2     2  Femenino       1       2    2
## 3     2 Masculino       1       2    1
## 4     2 Masculino Enfermo       2    2
## 5     2  Femenino       1       2    2
## Ident Género Salud Opinión Fuma
## 1 2 Masculino Enfermo 2 1
## 2 2 Femenino 1 2 2
## 3 2 Masculino 1 2 1
## 4 2 Masculino Enfermo 2 2
## 5 2 Femenino 1 2 2
reco1 <- Opin_Pacientes
reco1$Salud <- factor(reco1$Salud)
levels(reco1$Salud)[1] <- "Sano"
levels(reco1$Salud)[1] <- "Enfermo"
reco1
##   Ident    Genero   Salud Opinion Fuma
## 1     2 Masculino Enfermo       2    1
## 2     2  Femenino       1       2    2
## 3     2 Masculino       1       2    1
## 4     2 Masculino Enfermo       2    2
## 5     2  Femenino       1       2    2
## Ident Género Salud Opinión Fuma
## 1 2 Masculino Enfermo 2 1
## 2 2 Femenino 1 2 2
## 3 2 Masculino 1 2 1
## 4 2 Masculino Enfermo 2 2
## 5 2 Femenino 1 2 2
Opin_Pacientes$Genero <- ifelse(Opin_Pacientes$Genero == "Masculino",0,1)
Opin_Pacientes
##   Ident Genero Salud Opinion Fuma
## 1     2      0     0       2    1
## 2     2      1     1       2    2
## 3     2      0     1       2    1
## 4     2      0     0       2    2
## 5     2      1     1       2    2
## Ident Género Salud Opinión Fuma
## 1 2 0 0 2 1
## 2 2 1 1 2 2
## 3 2 0 1 2 1
## 4 2 0 0 2 2
## 5 2 1 1 2 2
library(car)
## Loading required package: carData
datos_reco <- data.frame(edad=c(22,21,34,40), sexo=c("H","M","H","H"))
edad_cod<- recode(datos_reco$edad, "15:25='joven';26:65='adulto'")
edad_cod
## [1] "joven"  "joven"  "adulto" "adulto"
#suprimimos warningS PARA VER VALORES
edad_cod<- recode(datos_reco$edad, suppressWarnings(as.numeric("15:25='joven';26:65='adulto'")))
edad_cod
## [1] 22 21 34 40
#Ejemplo 5:
 #definición de las variables en vectores
id=c(100,110,120,130,140,150,160,170,180,190)
edad=c(18,19,NA,18,24,27,22,25,22,15)
gen=c(2,1,2,2,1,2,1,1,2,1)
peso=c(65,58,56,61,84,99,50,64,87,87)
altura=c(161,170,174,165,150,171,181,170,184,190)
niv_col=c(1,2,3,1,3,2,3,1,2,3)
#tablas de frecuencias absolutas
table(edad)  
## edad
## 15 18 19 22 24 25 27 
##  1  2  1  2  1  1  1
## edad
## 15 18 19 22 24 25 27 
## 1 2 1 2 1 1 1
table(niv_col)
## niv_col
## 1 2 3 
## 3 3 4
## niv_col
## 1 2 3 
## 3 3 4
#El comando table() no  muestra los valores  faltantes  por defecto.    Así que debemos usar    el  
#siguiente  código:
table(edad, useNA="ifany") #utilizamos "useNA" para que aparezca NA
## edad
##   15   18   19   22   24   25   27 <NA> 
##    1    2    1    2    1    1    1    1
## edad
## 15 18 19 22 24 25 27 <NA> 
## 1 2 1 2 1 1 1 1
#tabla de frecuencias relativas
prop.table(edad)
##  [1] NA NA NA NA NA NA NA NA NA NA
## [1] NA NA NA NA NA NA NA NA NA NA
prop.table(altura)
##  [1] 0.09382284 0.09906760 0.10139860 0.09615385 0.08741259 0.09965035
##  [7] 0.10547786 0.09906760 0.10722611 0.11072261
## [1] 0.09382284 0.09906760 0.10139860 0.09615385 0.08741259 0.09965035
## [7] 0.10547786 0.09906760 0.10722611 0.11072261
#tabla de frecuencias absolutas cruzadas
table(niv_col,gen)
##        gen
## niv_col 1 2
##       1 1 2
##       2 1 2
##       3 3 1
## gen
## niv_col 1 2
## 1 1 2
## 2 1 2
## 3 3 1
#tabla de frecuencias relativas cruzadas
prop.table(table(niv_col,gen))
##        gen
## niv_col   1   2
##       1 0.1 0.2
##       2 0.1 0.2
##       3 0.3 0.1
## gen
## niv_col 1 2
## 1 0.1 0.2
## 2 0.1 0.2
## 3 0.3 0.1

data_cont <- table(niv_col,gen) #creamos la tabla de contingencia
chisq.test(data_cont) #aplicamos la prueba de la ji al cuadrado
## Warning in chisq.test(data_cont): Chi-squared approximation may be incorrect
## 
##  Pearson's Chi-squared test
## 
## data:  data_cont
## X-squared = 1.6667, df = 2, p-value = 0.4346
## Warning in chisq.test(data_cont): Chi-squared approximation may be incorrect
## 
## Pearson's Chi-squared test
## 
## data: data_cont
## X-squared = 1.6667, df = 2, p-value = 0.4346

'En caso    de  que al  realizar    la  prueba  de  la  ji  al  cuadrado    observemos  un  warning,    puede   ser 
debido  a   que los valores esperados   sean    menores que cinco,  o   la  proporción  supera  al  20 %    
de   las     celdas,     con     valores     observados  inferiores  a   cinco.  Cuando  esto    sucede,     es 
recomendable     utilizar    un  test    de  independencia   denominado  Fisher  con     el  comando    
fisher.test()'
## [1] "En\tcaso\tde\tque\tal\trealizar\tla\tprueba\tde\tla\tji\tal\tcuadrado\tobservemos\tun\twarning,\tpuede\tser\t\ndebido\ta\tque\tlos\tvalores\tesperados\tsean\tmenores\tque cinco,\to\tla\tproporción\tsupera\tal\t20 %\t\nde\t las\t celdas,\t con\t valores\t observados\t inferiores\t a\t cinco.\t Cuando\t esto\t sucede,\t es\t\nrecomendable\t utilizar\t un\t test\t de\t independencia\t denominado\t Fisher\t con\t el\t comando\t\nfisher.test()"
fisher.test(data_cont)
## 
##  Fisher's Exact Test for Count Data
## 
## data:  data_cont
## p-value = 0.5714
## alternative hypothesis: two.sided
## 
## Fisher's Exact Test for Count Data
## 
## data: data_cont
## p-value = 0.5714
## alternative hypothesis: two.sided

Including Plots

You can also embed plots, for example:

#Ejemplo 6:
plot(x=norm1, y=norm2, xlab="X", ylab="Y", xlim=c(-3,3), ylim=c(0,10), 
col=sample(colors(), 100)) #usamos las opciones para las etiquetas de los ejes, adaptamos sus límites y ponemos colores diferentes para los puntos

#Ejemplo 7:
#Otro    ejemplo     con     datos   simulados   para    ver     cómo    aplicamos  la   función     plot() en   gráficos estadísticos:
set.seed(999)
x1 <- rnorm(1000) #simulamos una variable x1
y1 <- x1 + rnorm(1000) #simulamos una variable y1 
plot(x1, y1, main="Gráfico de dispersión") #creamos el gráfico de dispersión de las variables
abline(lm(y1~x1), col="cadetblue3") #creamos la recta de regresión de color verde

plot(density(x1), main="Densidad de x1", col="aquamarine") #generamos el gráfico de densidad para ver cómo es la distribución
lines(density(y1), col="darkred") #generamos un gráfico con las densidades de las dos variables.

z1 <- seq(-10, 10, 0.01) #generamos datos con una secuencia
w1 <- sin(z1) #buscamos el sinus de nuestra variable
plot(z1,w1, col="darkred") #creamos el gráfico

boxplot(iris$Petal.Width, col="tomato", main="Diagrama de Caja del ancho del 
pétalo") #diagrama de caja de color rojo con un título

hist(iris$Sepal.Length, breaks=20, col="cadetblue3") #histograma con 20 intervalos de clase y color azul 

#aGRUPACIÓN DE GRÁFICOS
par(mfrow=c(2,2)) #matriz 2x2
hist(iris$Petal.Length, breaks=20, col="cadetblue3") #histograma
plot (iris$Sepal.Width, col="dark red", xlab="SepalWidth") #gráfico de dispersión
boxplot(iris$Petal.Width, col="tomato", main="Diagrama de Caja del ancho del 
pétalo") #diagrama de caja
plot (iris$Sepal.Width, col="dark red", xlab="SepalWidth") #gráfico de dispersión de color rojo oscuro

#aGRUPACIÓN DE GRÁFICOS
par(mfrow=c(2,2)) #matriz 2x2
hist(iris$Petal.Length, breaks=20, col="cadetblue3") #histograma
plot (iris$Sepal.Width, col="dark red", xlab="SepalWidth") #gráfico de dispersión
boxplot(iris$Petal.Width, col="tomato", main="Diagrama de Caja del ancho del 
pétalo") #diagrama de caja
plot (iris$Sepal.Width, col="dark red", xlab="SepalWidth") #gráfico de dispersión de color rojo oscuro

data_pie <- c(8,24,14,12,11,31) #datos inventados
pie(data_pie) #creamos un diagrama de sector

pie(data_pie, col=1:6, labels = c("0-15", "16-30", "31-45", "46-60", "61-75", 
"76-90")) #diagrama de sector y ponemos etiquetas a cada sector

##      Group.1 Sepal.Length Sepal.Width Petal.Length Petal.Width
## 1     setosa        5.006       3.428        1.462       0.246
## 2 versicolor        5.936       2.770        4.260       1.326
## 3  virginica        6.588       2.974        5.552       2.026

## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.5.0     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ✖ dplyr::recode() masks car::recode()
## ✖ dplyr::select() masks MASS::select()
## ✖ purrr::some()   masks car::some()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors

library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:MASS':
## 
##     select
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
graf1 <- plot_ly(y = ~rnorm(100), type = "box")
graf2 <- graf1 %>% add_trace(y = ~rnorm(100, 1))
graf2
#pdf("migrafico.pdf") #abrimos el dispositivo gráfico
#plot(iris$Petal.Width)
#dev.off #cerramos el dispositivo gráfico
#file.show("migrafico.pdf") #podemos visualizar el archivo que hemos generado
#Ejemplo 13
library(knitr)
id <- seq(1:25)
peso <- c(63, 72, 79, 75, 27, 84, 73,65, 70, 76, 69, 89,65,57,59, 69, 60, 79, 
75, 82, 59, 67, 85, 55,63)
grasa <- c(288,385,402, 365, 209, 354, 190, 405, 263, 451, 
302,290,346,254,395,434,220,374,308,220,311,181,274,303,244 )
edad <- c(28,36,57, 44, 24,46,20, 52, 30, 57, 
25,31,52,23,60,48,34,51,50,34,46,23,37,40,30)
Mujeres <- data.frame(id, peso, grasa, edad)
head(Mujeres)
##   id peso grasa edad
## 1  1   63   288   28
## 2  2   72   385   36
## 3  3   79   402   57
## 4  4   75   365   44
## 5  5   27   209   24
## 6  6   84   354   46
## id peso grasa edad
## 1 1 63 288 28
## 2 2 72 385 36
## 3 3 79 402 57
## 4 4 75 365 44
## 5 5 27 209 24
## 6 6 84 354 46
names(Mujeres)
## [1] "id"    "peso"  "grasa" "edad"
## [1] "id" "peso" "grasa" "edad"

str(Mujeres)
## 'data.frame':    25 obs. of  4 variables:
##  $ id   : int  1 2 3 4 5 6 7 8 9 10 ...
##  $ peso : num  63 72 79 75 27 84 73 65 70 76 ...
##  $ grasa: num  288 385 402 365 209 354 190 405 263 451 ...
##  $ edad : num  28 36 57 44 24 46 20 52 30 57 ...
## 'data.frame': 25 obs. of 4 variables:
## $ id: int 1 2 3 4 5 6 7 8 9 10 ...
## $ peso: núm. 63 72 79 75 27 84 73 65 70 76 ...
## $ grasa: núm. 288 385 402 365 209 354 190 405 263 451 ...
## $ edad: núm. 28 36 57 44 24 46 20 52 30 57 ...
summary(Mujeres)
##        id          peso           grasa            edad      
##  Min.   : 1   Min.   :27.00   Min.   :181.0   Min.   :20.00  
##  1st Qu.: 7   1st Qu.:63.00   1st Qu.:254.0   1st Qu.:30.00  
##  Median :13   Median :69.00   Median :303.0   Median :37.00  
##  Mean   :13   Mean   :68.68   Mean   :310.7   Mean   :39.12  
##  3rd Qu.:19   3rd Qu.:76.00   3rd Qu.:374.0   3rd Qu.:50.00  
##  Max.   :25   Max.   :89.00   Max.   :451.0   Max.   :60.00
## id peso grasa edad 
## Min. : 1 Min. :27.00 Min. :181.0 Min. :20.00 
## 1st Qu.: 7 1st Qu.:63.00 1st Qu.:254.0 1st Qu.:30.00 
## Median :13 Median :69.00 Median :303.0 Median :37.00 
## Mean :13 Mean :68.68 Mean :310.7 Mean :39.12 
## 3rd Qu.:19 3rd Qu.:76.00 3rd Qu.:374.0 3rd Qu.:50.00 
## Max. :25 Max. :89.00 Max. :451.0 Max. :60.00
pairs(Mujeres)

kable(cor(Mujeres$grasa, Mujeres$edad))
x
0.8373534
modelreg <- lm(grasa ~ edad, data = Mujeres) 
summary(modelreg) 
## 
## Call:
## lm(formula = grasa ~ edad, data = Mujeres)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -63.478 -26.816  -3.854  28.315  90.881 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 102.5751    29.6376   3.461  0.00212 ** 
## edad          5.3207     0.7243   7.346 1.79e-07 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 43.46 on 23 degrees of freedom
## Multiple R-squared:  0.7012, Adjusted R-squared:  0.6882 
## F-statistic: 53.96 on 1 and 23 DF,  p-value: 1.794e-07
## 
## Call:
## lm(formula = grasa ~ edad, data = Mujeres)
## 
## Residuals:
## Min 1Q Median 3Q Max 
## -63.478 -26.816 -3.854 28.315 90.881 
## 
## Coefficients:
## Estimate Std. Error t value Pr(>|t|) 
## (Intercept) 102.5751 29.6376 3.461 0.00212 ** 
## edad 5.3207 0.7243 7.346 1.79e-07 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 43.46 on 23 degrees of freedom
## Multiple R-squared: 0.7012, Adjusted R-squared: 0.6882 
## F-statistic: 53.96 on 1 and 23 DF, p-value: 1.794e-07
###y=102.575+5.321x
plot(Mujeres$edad, Mujeres$grasa, xlab='Edad', ylab='Grasa')
abline(modelreg)

residuos <- rstandard(modelreg)
valores.ajustados <- fitted(modelreg)
plot(valores.ajustados, residuos)

qqnorm(residuos)
qqline(residuos)

pred_edad <- data.frame(edad = seq(30, 40))
predict(modelreg, pred_edad)
##        1        2        3        4        5        6        7        8 
## 262.1954 267.5161 272.8368 278.1575 283.4781 288.7988 294.1195 299.4402 
##        9       10       11 
## 304.7608 310.0815 315.4022
## 1 2 3 4 5 6 7 8 
## 262.1954 267.5161 272.8368 278.1575 283.4781 288.7988 294.1195 299.4402 
## 9 10 11 
## 304.7608 310.0815 315.4022

confint(modelreg) #por defecto el intervalo es del 95 %
##                 2.5 %     97.5 %
## (Intercept) 41.265155 163.885130
## edad         3.822367   6.818986
## 2.5 % 97.5 %
## (Intercept) 41.265155 163.885130
## edad 3.822367 6.818986
confint(modelreg, level=0.90) #con intervalo de confianza del 90 %
##                   5 %       95 %
## (Intercept) 51.780153 153.370132
## edad         4.079335   6.562018
## 5 % 95 %
## (Intercept) 51.780153 153.370132
## edad 4.079335 6.562018
#Ejemplo 14
#activar los datos y observar cómo son los tipos de datos y las variables con resúmenes estadísticos
library(knitr)
datos_usa <- data.frame(state.x77)
str(datos_usa)
## 'data.frame':    50 obs. of  8 variables:
##  $ Population: num  3615 365 2212 2110 21198 ...
##  $ Income    : num  3624 6315 4530 3378 5114 ...
##  $ Illiteracy: num  2.1 1.5 1.8 1.9 1.1 0.7 1.1 0.9 1.3 2 ...
##  $ Life.Exp  : num  69 69.3 70.5 70.7 71.7 ...
##  $ Murder    : num  15.1 11.3 7.8 10.1 10.3 6.8 3.1 6.2 10.7 13.9 ...
##  $ HS.Grad   : num  41.3 66.7 58.1 39.9 62.6 63.9 56 54.6 52.6 40.6 ...
##  $ Frost     : num  20 152 15 65 20 166 139 103 11 60 ...
##  $ Area      : num  50708 566432 113417 51945 156361 ...
## 'data.frame': 50 obs. of 8 variables:
## $ Population: núm. 3615 365 2212 2110 21198 ...
## $ Income : núm. 3624 6315 4530 3378 5114 ...
## $ Illiteracy: núm. 2.1 1.5 1.8 1.9 1.1 0.7 1.1 0.9 1.3 2 ...
## $ Life.Exp : núm. 69 69.3 70.5 70.7 71.7 ...
## $ Murder : núm. 15.1 11.3 7.8 10.1 10.3 6.8 3.1 6.2 10.7 13.9 ...
## $ HS.Grad : núm. 41.3 66.7 58.1 39.9 62.6 63.9 56 54.6 52.6 40.6 ...
## $ Frost : núm. 20 152 15 65 20 166 139 103 11 60 ...
## $ Area : núm. 50708 566432 113417 51945 156361 ...
summary(datos_usa) #resumen de los datos
##    Population        Income       Illiteracy       Life.Exp    
##  Min.   :  365   Min.   :3098   Min.   :0.500   Min.   :67.96  
##  1st Qu.: 1080   1st Qu.:3993   1st Qu.:0.625   1st Qu.:70.12  
##  Median : 2838   Median :4519   Median :0.950   Median :70.67  
##  Mean   : 4246   Mean   :4436   Mean   :1.170   Mean   :70.88  
##  3rd Qu.: 4968   3rd Qu.:4814   3rd Qu.:1.575   3rd Qu.:71.89  
##  Max.   :21198   Max.   :6315   Max.   :2.800   Max.   :73.60  
##      Murder          HS.Grad          Frost             Area       
##  Min.   : 1.400   Min.   :37.80   Min.   :  0.00   Min.   :  1049  
##  1st Qu.: 4.350   1st Qu.:48.05   1st Qu.: 66.25   1st Qu.: 36985  
##  Median : 6.850   Median :53.25   Median :114.50   Median : 54277  
##  Mean   : 7.378   Mean   :53.11   Mean   :104.46   Mean   : 70736  
##  3rd Qu.:10.675   3rd Qu.:59.15   3rd Qu.:139.75   3rd Qu.: 81163  
##  Max.   :15.100   Max.   :67.30   Max.   :188.00   Max.   :566432
## Population Income Illiteracy Life.Exp 
## Min. : 365 Min. :3098 Min. :0.500 Min. :67.96 
## 1st Qu.: 1080 1st Qu.:3993 1st Qu.:0.625 1st Qu.:70.12 
## Median : 2838 Median :4519 Median :0.950 Median :70.67 
## Mean : 4246 Mean :4436 Mean :1.170 Mean :70.88 
## 3rd Qu.: 4968 3rd Qu.:4814 3rd Qu.:1.575 3rd Qu.:71.89 
## Max. :21198 Max. :6315 Max. :2.800 Max. :73.60 
## Murder HS.Grad Frost Area
## Min. : 1.400 Min. :37.80 Min. : 0.00 Min. : 1049 
## 1st Qu.: 4.350 1st Qu.:48.05 1st Qu.: 66.25 1st Qu.: 36985 
## Median : 6.850 Median :53.25 Median :114.50 Median : 54277 
## Mean : 7.378 Mean :53.11 Mean :104.46 Mean : 70736 
## 3rd Qu.:10.675 3rd Qu.:59.15 3rd Qu.:139.75 3rd Qu.: 81163 
## Max. :15.100 Max. :67.30 Max. :188.00 Max. :566432
Density_population <- datos_usa$Population * 1000 / datos_usa$Area
datos_usa2 <- cbind(datos_usa,Density_population) #unimos el conjunto de datos con la nueva variable de densidad de población
cor_usa2<-cor(datos_usa2)
as.data.frame(cor_usa2)
##                     Population     Income   Illiteracy    Life.Exp     Murder
## Population          1.00000000  0.2082276  0.107622373 -0.06805195  0.3436428
## Income              0.20822756  1.0000000 -0.437075186  0.34025534 -0.2300776
## Illiteracy          0.10762237 -0.4370752  1.000000000 -0.58847793  0.7029752
## Life.Exp           -0.06805195  0.3402553 -0.588477926  1.00000000 -0.7808458
## Murder              0.34364275 -0.2300776  0.702975199 -0.78084575  1.0000000
## HS.Grad            -0.09848975  0.6199323 -0.657188609  0.58221620 -0.4879710
## Frost              -0.33215245  0.2262822 -0.671946968  0.26206801 -0.5388834
## Area                0.02254384  0.3633154  0.077261132 -0.10733194  0.2283902
## Density_population  0.24622789  0.3299683  0.009274348  0.09106176 -0.1850352
##                        HS.Grad        Frost        Area Density_population
## Population         -0.09848975 -0.332152454  0.02254384        0.246227888
## Income              0.61993232  0.226282179  0.36331544        0.329968277
## Illiteracy         -0.65718861 -0.671946968  0.07726113        0.009274348
## Life.Exp            0.58221620  0.262068011 -0.10733194        0.091061763
## Murder             -0.48797102 -0.538883437  0.22839021       -0.185035233
## HS.Grad             1.00000000  0.366779702  0.33354187       -0.088367214
## Frost               0.36677970  1.000000000  0.05922910        0.002276734
## Area                0.33354187  0.059229102  1.00000000       -0.341388515
## Density_population -0.08836721  0.002276734 -0.34138851        1.000000000
## Population Income Illiteracy Life.Exp Murder
## Population 1.00000000 0.2082276 0.107622373 -0.06805195 0.3436428
## Income 0.20822756 1.0000000 -0.437075186 0.34025534 -0.2300776
## Illiteracy 0.10762237 -0.4370752 1.000000000 -0.58847793 0.7029752
## Life.Exp -0.06805195 0.3402553 -0.588477926 1.00000000 -0.7808458
## Murder 0.34364275 -0.2300776 0.702975199 -0.78084575 1.0000000
## HS.Grad -0.09848975 0.6199323 -0.657188609 0.58221620 -0.4879710
## Frost -0.33215245 0.2262822 -0.671946968 0.26206801 -0.5388834
## Area 0.02254384 0.3633154 0.077261132 -0.10733194 0.2283902
## Density_population 0.24622789 0.3299683 0.009274348 0.09106176 -0.1850352
## HS.Grad Frost Area Density_population
## Population -0.09848975 -0.332152454 0.02254384 0.246227888
## Income 0.61993232 0.226282179 0.36331544 0.329968277
## Illiteracy -0.65718861 -0.671946968 0.07726113 0.009274348
## Life.Exp 0.58221620 0.262068011 -0.10733194 0.091061763
## Murder -0.48797102 -0.538883437 0.22839021 -0.185035233
## HS.Grad 1.00000000 0.366779702 0.33354187 -0.088367214
## Frost 0.36677970 1.000000000 0.05922910 0.002276734
## Area 0.33354187 0.059229102 1.00000000 -0.341388515
## Density_population -0.08836721 0.002276734 -0.34138851 1.000000000
kable(cor_usa2) #miramos la tabla con las correlaciones
Population Income Illiteracy Life.Exp Murder HS.Grad Frost Area Density_population
Population 1.0000000 0.2082276 0.1076224 -0.0680520 0.3436428 -0.0984897 -0.3321525 0.0225438 0.2462279
Income 0.2082276 1.0000000 -0.4370752 0.3402553 -0.2300776 0.6199323 0.2262822 0.3633154 0.3299683
Illiteracy 0.1076224 -0.4370752 1.0000000 -0.5884779 0.7029752 -0.6571886 -0.6719470 0.0772611 0.0092743
Life.Exp -0.0680520 0.3402553 -0.5884779 1.0000000 -0.7808458 0.5822162 0.2620680 -0.1073319 0.0910618
Murder 0.3436428 -0.2300776 0.7029752 -0.7808458 1.0000000 -0.4879710 -0.5388834 0.2283902 -0.1850352
HS.Grad -0.0984897 0.6199323 -0.6571886 0.5822162 -0.4879710 1.0000000 0.3667797 0.3335419 -0.0883672
Frost -0.3321525 0.2262822 -0.6719470 0.2620680 -0.5388834 0.3667797 1.0000000 0.0592291 0.0022767
Area 0.0225438 0.3633154 0.0772611 -0.1073319 0.2283902 0.3335419 0.0592291 1.0000000 -0.3413885
Density_population 0.2462279 0.3299683 0.0092743 0.0910618 -0.1850352 -0.0883672 0.0022767 -0.3413885 1.0000000
model_reg_mult <- lm(Life.Exp ~ Population + Income + Illiteracy + Murder +
HS.Grad + Frost + Area + Density_population, data =
datos_usa2) #modelo con todas las variables
summary(model_reg_mult) #resumen del modelo con todas las variables
## 
## Call:
## lm(formula = Life.Exp ~ Population + Income + Illiteracy + Murder + 
##     HS.Grad + Frost + Area + Density_population, data = datos_usa2)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -1.47514 -0.45887 -0.06352  0.59362  1.21823 
## 
## Coefficients:
##                      Estimate Std. Error t value Pr(>|t|)    
## (Intercept)         6.995e+01  1.843e+00  37.956  < 2e-16 ***
## Population          6.480e-05  3.001e-05   2.159   0.0367 *  
## Income              2.701e-04  3.087e-04   0.875   0.3867    
## Illiteracy          3.029e-01  4.024e-01   0.753   0.4559    
## Murder             -3.286e-01  4.941e-02  -6.652 5.12e-08 ***
## HS.Grad             4.291e-02  2.332e-02   1.840   0.0730 .  
## Frost              -4.580e-03  3.189e-03  -1.436   0.1585    
## Area               -1.558e-06  1.914e-06  -0.814   0.4205    
## Density_population -1.105e-03  7.312e-04  -1.511   0.1385    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.7337 on 41 degrees of freedom
## Multiple R-squared:  0.7501, Adjusted R-squared:  0.7013 
## F-statistic: 15.38 on 8 and 41 DF,  p-value: 3.787e-10
## 
## Call:
## lm(formula = Life.Exp ~ Population + Income + Illiteracy + Murder + 
## HS.Grad + Frost + Area + Density_population, data = datos_usa2)
## 
## Residuals:
## Min 1Q Median 3Q Max 
## -1.47514 -0.45887 -0.06352 0.59362 1.21823 
## 
## Coefficients:
## Estimate Std. Error t value Pr(>|t|) 
## (Intercept) 6.995e+01 1.843e+00 37.956 < 2e-16 ***
## Population 6.480e-05 3.001e-05 2.159 0.0367 * 
## Income 2.701e-04 3.087e-04 0.875 0.3867 
## Illiteracy 3.029e-01 4.024e-01 0.753 0.4559 
## Murder -3.286e-01 4.941e-02 -6.652 5.12e-08 ***
## HS.Grad 4.291e-02 2.332e-02 1.840 0.0730 . 
## Frost -4.580e-03 3.189e-03 -1.436 0.1585
## Area -1.558e-06 1.914e-06 -0.814 0.4205
## Density_population -1.105e-03 7.312e-04 -1.511 0.1385
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.7337 on 41 degrees of freedom
## Multiple R-squared: 0.7501, Adjusted R-squared: 0.7013 
## F-statistic: 15.38 on 8 and 41 DF, p-value: 3.787e-10step(object=model_reg_mult, direction="both", trace=1) 
## Start: AIC=-22.89
## Life.Exp ~ Population + Income + Illiteracy + Murder + HS.Grad + 
## Frost + Area + Density_population
## 
## Df Sum of Sq RSS AIC
## - Illiteracy 1 0.3050 22.373 -24.208
## - Area 1 0.3564 22.425 -24.093
## - Income 1 0.4120 22.480 -23.969
## <none> 22.068 -22.894
## - Frost 1 1.1102 23.178 -22.440
## - Density_population 1 1.2288 23.297 -22.185
## - HS.Grad 1 1.8225 23.891 -20.926
## - Population 1 2.5095 24.578 -19.509
## - Murder 1 23.8173 45.886 11.707
## 
## Step: AIC=-24.21
## Life.Exp ~ Population + Income + Murder + HS.Grad + Frost + Area + 
## Density_population
## 
## Df Sum of Sq RSS AIC
## - Area 1 0.1427 22.516 -25.890
## - Income 1 0.2316 22.605 -25.693
## <none> 22.373 -24.208
## - Density_population 1 0.9286 23.302 -24.174
## - HS.Grad 1 1.5218 23.895 -22.918
## + Illiteracy 1 0.3050 22.068 -22.894
## - Population 1 2.2047 24.578 -21.509
## - Frost 1 3.1324 25.506 -19.656
## - Murder 1 26.7071 49.080 13.072© FUOC • PID_00293463 37 Estadística descriptiva y gráficos con R
## 
## Step: AIC=-25.89
## Life.Exp ~ Population + Income + Murder + HS.Grad + Frost + Density_population
## 
## Df Sum of Sq RSS AIC
## - Income 1 0.132 22.648 -27.598
## - Density_population 1 0.786 23.302 -26.174
## <none> 22.516 -25.890
## - HS.Grad 1 1.424 23.940 -24.824
## + Area 1 0.143 22.373 -24.208
## + Illiteracy 1 0.091 22.425 -24.093
## - Population 1 2.332 24.848 -22.962
## - Frost 1 3.304 25.820 -21.043
## - Murder 1 32.779 55.295 17.033
## 
## Step: AIC=-27.6
## Life.Exp ~ Population + Murder + HS.Grad + Frost + Density_population
## 
## Df Sum of Sq RSS AIC
## - Density_population 1 0.660 23.308 -28.161
## <none> 22.648 -27.598
## + Income 1 0.132 22.516 -25.890
## + Illiteracy 1 0.061 22.587 -25.732
## + Area 1 0.043 22.605 -25.693
## - Population 1 2.659 25.307 -24.046
## - Frost 1 3.179 25.827 -23.030
## - HS.Grad 1 3.966 26.614 -21.529
## - Murder 1 33.626 56.274 15.910
## 
## Step: AIC=-28.16
## Life.Exp ~ Population + Murder + HS.Grad + Frost
## 
## Df Sum of Sq RSS AIC
## <none> 23.308 -28.161
## + Density_population 1 0.660 22.648 -27.598
## + Income 1 0.006 23.302 -26.174
## + Illiteracy 1 0.004 23.304 -26.170
## + Area 1 0.001 23.307 -26.163
## - Population 1 2.064 25.372 -25.920
## - Frost 1 3.122 26.430 -23.877
## - HS.Grad 1 5.112 28.420 -20.246
## - Murder 1 34.816 58.124 15.528
## 
## Call:
## lm(formula = Life.Exp ~ Population + Murder + HS.Grad + Frost, 
## data = datos_usa2)
## 
## Coefficients:© FUOC • PID_00293463 38 Estadística descriptiva y gráficos con R
## (Intercept) Population Murder HS.Grad Frost 
## 7.103e+01 5.014e-05 -3.001e-01 4.658e-02 -5.943e-03
model_reg_mult2 <- (lm(formula = Life.Exp ~ Population + Murder + HS.Grad +
Frost, data = datos_usa2))
summary(model_reg_mult2) #resultados con el modelo final
## 
## Call:
## lm(formula = Life.Exp ~ Population + Murder + HS.Grad + Frost, 
##     data = datos_usa2)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -1.47095 -0.53464 -0.03701  0.57621  1.50683 
## 
## Coefficients:
##               Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  7.103e+01  9.529e-01  74.542  < 2e-16 ***
## Population   5.014e-05  2.512e-05   1.996  0.05201 .  
## Murder      -3.001e-01  3.661e-02  -8.199 1.77e-10 ***
## HS.Grad      4.658e-02  1.483e-02   3.142  0.00297 ** 
## Frost       -5.943e-03  2.421e-03  -2.455  0.01802 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.7197 on 45 degrees of freedom
## Multiple R-squared:  0.736,  Adjusted R-squared:  0.7126 
## F-statistic: 31.37 on 4 and 45 DF,  p-value: 1.696e-12
## 
## Call:
## lm(formula = Life.Exp ~ Population + Murder + HS.Grad + Frost, 
## data = datos_usa2)
## 
## Residuals:
## Min 1Q Median 3Q Max 
## -1.47095 -0.53464 -0.03701 0.57621 1.50683 
## 
## Coefficients:
## Estimate Std. Error t value Pr(>|t|) 
## (Intercept) 7.103e+01 9.529e-01 74.542 < 2e-16 ***
## Population 5.014e-05 2.512e-05 1.996 0.05201 . 
## Murder -3.001e-01 3.661e-02 -8.199 1.77e-10 ***
## HS.Grad 4.658e-02 1.483e-02 3.142 0.00297 ** 
## Frost -5.943e-03 2.421e-03 -2.455 0.01802 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.7197 on 45 degrees of freedom
## Multiple R-squared: 0.736, Adjusted R-squared: 0.7126 
## F-statistic: 31.37 on 4 and 45 DF, p-value: 1.696e-12
Valores_predic <- data.frame(Population = 7000,
Murder = 5, HS.Grad = 45, Frost = 120 )
Valores_predic
##   Population Murder HS.Grad Frost
## 1       7000      5      45   120
## Population Murder HS.Grad Frost
## 1 7000 5 45 120
predicción <- predict(model_reg_mult2, newdata = Valores_predic)
predicción
##        1 
## 71.26037
## 1 
## 71.26037
#install.packages("WRS2") #instalar la librería
library (WRS2)
data("goggles") #activar datos
head("goggles") #primeros registros
## [1] "goggles"
## [1] "goggles"
summary(goggles)
##     gender      alcohol   attractiveness 
##  Female:24   None   :16   Min.   :20.00  
##  Male  :24   2 Pints:16   1st Qu.:53.75  
##              4 Pints:16   Median :60.00  
##                           Mean   :58.33  
##                           3rd Qu.:66.25  
##                           Max.   :85.00
## gender alcohol attractiveness 
## Female:24 None :16 Min. :20.00 
## Male :24 2 Pints:16 1st Qu.:53.75 
## 4 Pints:16 Median :60.00 
## Mean :58.33 
## 3rd Qu.:66.25 
## Max. :85.00
 #install.packages("psych")
library(psych)
## 
## Attaching package: 'psych'
## The following objects are masked from 'package:ggplot2':
## 
##     %+%, alpha
## The following object is masked from 'package:car':
## 
##     logit
describeBy(goggles$attractiveness, goggles$alcohol)
## 
##  Descriptive statistics by group 
## group: None
##    vars  n  mean   sd median trimmed   mad min max range skew kurtosis   se
## X1    1 16 63.75 8.47   62.5   63.57 11.12  50  80    30 0.29    -1.07 2.12
## ------------------------------------------------------------ 
## group: 2 Pints
##    vars  n  mean   sd median trimmed  mad min max range skew kurtosis   se
## X1    1 16 64.69 9.91     65   64.64 7.41  45  85    40 0.08    -0.23 2.48
## ------------------------------------------------------------ 
## group: 4 Pints
##    vars  n  mean    sd median trimmed   mad min max range  skew kurtosis   se
## X1    1 16 46.56 14.34     50   46.79 14.83  20  70    50 -0.22    -1.21 3.59
## 
## Descriptive statistics by group 
## group: None
## vars n mean sd median trimmed mad min max range skew kurtosis se
## X1 1 16 63.75 8.47 62.5 63.57 11.12 50 80 30 0.29 -1.07 2.12
## ------------------------------------------------------------
## group: 2 Pints
## vars n mean sd median trimmed mad min max range skew kurtosis se
## X1 1 16 64.69 9.91 65 64.64 7.41 45 85 40 0.08 -0.23 2.48
## ------------------------------------------------------------
## group: 4 Pints
## vars n mean sd median trimmed mad min max range skew kurtosis se
## X1 1 16 46.56 14.34 50 46.79 14.83 20 70 50 -0.22 -1.21 3.59
boxplot(goggles$attractiveness ~ goggles$alcohol, col=palette.colors())

by(goggles$attractiveness, goggles$alcohol, shapiro.test) #normalidad
## goggles$alcohol: None
## 
##  Shapiro-Wilk normality test
## 
## data:  dd[x, ]
## W = 0.95498, p-value = 0.5725
## 
## ------------------------------------------------------------ 
## goggles$alcohol: 2 Pints
## 
##  Shapiro-Wilk normality test
## 
## data:  dd[x, ]
## W = 0.94489, p-value = 0.4132
## 
## ------------------------------------------------------------ 
## goggles$alcohol: 4 Pints
## 
##  Shapiro-Wilk normality test
## 
## data:  dd[x, ]
## W = 0.952, p-value = 0.522
## goggles$alcohol: None
## 
## Shapiro-Wilk normality test
## 
## data: dd[x, ]
## W = 0.95498, p-value = 0.5725
##
## ------------------------------------------------------------
## goggles$alcohol: 2 Pints
## 
## Shapiro-Wilk normality test
## 
## data: dd[x, ]
## W = 0.94489, p-value = 0.4132
## 
## ------------------------------------------------------------
## goggles$alcohol: 4 Pints
## 
## Shapiro-Wilk normality test
## 
## data: dd[x, ]
## W = 0.952, p-value = 0.522
bartlett.test(goggles$attractiveness, goggles$alcohol) #varianza homogénea
## 
##  Bartlett test of homogeneity of variances
## 
## data:  goggles$attractiveness and goggles$alcohol
## Bartlett's K-squared = 4.4295, df = 2, p-value = 0.1092
## 
## Bartlett test of homogeneity of variances
## 
## data: goggles$attractiveness and goggles$alcohol
## Bartlett's K-squared = 4.4295, df = 2, p-value = 0.1092
#levene.test (goggles$attractiveness, goggles$alcohol) #varianza homogénea pero más sensible a las desviaciones de la normalidad
model_anov <- aov(attractiveness ~ alcohol, data= goggles)
summary (model_anov)
##             Df Sum Sq Mean Sq F value   Pr(>F)    
## alcohol      2   3332  1666.1   13.31 2.88e-05 ***
## Residuals   45   5634   125.2                     
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## Df Sum Sq Mean Sq F value Pr(>F) 
## alcohol 2 3332 1666.1 13.31 2.88e-05 ***
## Residuals 45 5634 125.2
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 
TukeyHSD(model_anov)
##   Tukey multiple comparisons of means
##     95% family-wise confidence level
## 
## Fit: aov(formula = attractiveness ~ alcohol, data = goggles)
## 
## $alcohol
##                     diff        lwr       upr     p adj
## 2 Pints-None      0.9375  -8.650654 10.525654 0.9695381
## 4 Pints-None    -17.1875 -26.775654 -7.599346 0.0002283
## 4 Pints-2 Pints -18.1250 -27.713154 -8.536846 0.0001067
## Tukey multiple comparisons of means
## 95% family-wise confidence level
## 
## Fit: aov(formula = attractiveness ~ alcohol, data = goggles)
## 
## $alcohol
## diff lwr upr p adj
## 2 Pints-None 0.9375 -8.650654 10.525654 0.9695381
## 4 Pints-None -17.1875 -26.775654 -7.599346 0.0002283
## 4 Pints-2 Pints -18.1250 -27.713154 -8.536846 0.0001067