install.packages("tidyverse", repos = "http://cran.us.r-project.org")##
## The downloaded binary packages are in
## /var/folders/n1/zsbrkfs97sd_4fdl4mnf21g00000gn/T//RtmpzEq3VB/downloaded_packages
library(tidyverse)Para calcular la media aritmética de un vector podemos utilizar la
función mean.
# vector de muestra
x <- c(2, 4, 3, 6, 3, 7, 5, 8, 12, 23, 24, 27)
# uso de mean
mean(x) # 10.33## [1] 10.33333
# Equivalente a:
sum(x)/length(x) # 10.33## [1] 10.33333
Si hay valores nulos o ausentes presenta errores.
x <- c(2, 4, 3, 6, 3, 7, 5, 8, 12, 23, 24, 27, NA)
# Si el vector contiene algún valor NA, el resultado será NA
mean(x) # NA## [1] NA
# Eliminar los valores NA
mean(x, na.rm = TRUE) # 10.33## [1] 10.33333
La media aritmética truncada elimina una fracción de las observaciones de cada lado del vector antes de que se calcule la media. Para descartar valores atípicos.
x <- c(2, 4, 3, 6, 3, 7, 5, 8, 12, 23, 24, 27)
mean(x) # 10.33## [1] 10.33333
# Media aritmética truncada al 10%
# (elimina el primer y último elemento en este ejemplo)
mean(x, trim = 0.1) # 9.5## [1] 9.5
La media geométrica es la raíz n-ésima del producto de los elementos
del vector. Para calcularla puedes usar las funciones exp,
mean y log.
g <- c(2, 4, 3, 6, 3, 7, 5, 8, 12, 23, 24, 27)
# Media geométrica
exp(mean(log(g))) # 7.265416## [1] 7.265416
La desviación típica y la varianza son medidas de dispersión que cuantifican el grado de variabilidad de una variable. Junto con las medidas de tendencia central, las medidas estadísticas de dispersión se usan para describir las propiedades de una distribución.
g <- c(2, 4, 3, 6, 3, 7, 5, 8, 12, 23, 24, 27)
# Varianza
var(g) # 82.60606## [1] 82.60606
# Desviación típica
sd(g) # 9.088788## [1] 9.088788
# Equivalente a:
sqrt(var(x))## [1] 9.088788
La moda es una medida de localización que se define como el valor más probable de una variable aleatoria o como el valor más frecuente de un conjunto de observaciones. Es una medida robusta que coincide con la media y con la mediana en distribuciones simétricas.
g <- c(2, 4, 3, 6, 3, 7, 5, 3, 12, 23, 24, 27)
mode <- function(x) {
return(as.numeric(names(which.max(table(x)))))
}
mode(g)## [1] 3
barplot(table(g), col = c(4, rep("gray", 4)))
legend("topright", "Moda", fill = 4)La moda puede tomar varios valores a la vez.
g <- c(2, 4, 3, 6, 3, 7, 5, 3, 6, 23, 24, 27,6)
# Histograma
hist(g)Los vectores de tipo lógico solo pueden contener 3 valores posibles: TRUE, FALSE y NA. Generalmente no se encuentran de froma natural en lo s datos originales a trabajar pero suelen ser resultados de operaciones o búsquedas de datos.
Para las siguientes operaciones se usarán los datos de vuelo de nueva York (nycflights13).
install.packages("nycflights13", repos = "http://cran.us.r-project.org")##
## The downloaded binary packages are in
## /var/folders/n1/zsbrkfs97sd_4fdl4mnf21g00000gn/T//RtmpzEq3VB/downloaded_packages
library(nycflights13)datos de vuelo:
head(flights)## # A tibble: 6 × 19
## year month day dep_time sched_dep…¹ dep_d…² arr_t…³ sched…⁴ arr_d…⁵ carrier
## <int> <int> <int> <int> <int> <dbl> <int> <int> <dbl> <chr>
## 1 2013 1 1 517 515 2 830 819 11 UA
## 2 2013 1 1 533 529 4 850 830 20 UA
## 3 2013 1 1 542 540 2 923 850 33 AA
## 4 2013 1 1 544 545 -1 1004 1022 -18 B6
## 5 2013 1 1 554 600 -6 812 837 -25 DL
## 6 2013 1 1 554 558 -4 740 728 12 UA
## # … with 9 more variables: flight <int>, tailnum <chr>, origin <chr>,
## # dest <chr>, air_time <dbl>, distance <dbl>, hour <dbl>, minute <dbl>,
## # time_hour <dttm>, and abbreviated variable names ¹sched_dep_time,
## # ²dep_delay, ³arr_time, ⁴sched_arr_time, ⁵arr_delay
str(flights)## tibble [336,776 × 19] (S3: tbl_df/tbl/data.frame)
## $ year : int [1:336776] 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 ...
## $ month : int [1:336776] 1 1 1 1 1 1 1 1 1 1 ...
## $ day : int [1:336776] 1 1 1 1 1 1 1 1 1 1 ...
## $ dep_time : int [1:336776] 517 533 542 544 554 554 555 557 557 558 ...
## $ sched_dep_time: int [1:336776] 515 529 540 545 600 558 600 600 600 600 ...
## $ dep_delay : num [1:336776] 2 4 2 -1 -6 -4 -5 -3 -3 -2 ...
## $ arr_time : int [1:336776] 830 850 923 1004 812 740 913 709 838 753 ...
## $ sched_arr_time: int [1:336776] 819 830 850 1022 837 728 854 723 846 745 ...
## $ arr_delay : num [1:336776] 11 20 33 -18 -25 12 19 -14 -8 8 ...
## $ carrier : chr [1:336776] "UA" "UA" "AA" "B6" ...
## $ flight : int [1:336776] 1545 1714 1141 725 461 1696 507 5708 79 301 ...
## $ tailnum : chr [1:336776] "N14228" "N24211" "N619AA" "N804JB" ...
## $ origin : chr [1:336776] "EWR" "LGA" "JFK" "JFK" ...
## $ dest : chr [1:336776] "IAH" "IAH" "MIA" "BQN" ...
## $ air_time : num [1:336776] 227 227 160 183 116 150 158 53 140 138 ...
## $ distance : num [1:336776] 1400 1416 1089 1576 762 ...
## $ hour : num [1:336776] 5 5 5 5 6 5 6 6 6 6 ...
## $ minute : num [1:336776] 15 29 40 45 0 58 0 0 0 0 ...
## $ time_hour : POSIXct[1:336776], format: "2013-01-01 05:00:00" "2013-01-01 05:00:00" ...
Estableciendo un filtro con el uso de mutate (parte de tidyverse). Se crean dos columna nuevas; daytime y ontime.
daytime: para aquellos vuelos que salieron entre las 6 y las 20 horas.
ontime: los vuelos con un retraso menor a 20 minutos.
flights %>%
mutate(
daytime = dep_time > 600 & dep_time < 2000,
ontime = abs(arr_delay) < 20,
.keep = "used"
)## # A tibble: 336,776 × 4
## dep_time arr_delay daytime ontime
## <int> <dbl> <lgl> <lgl>
## 1 517 11 FALSE TRUE
## 2 533 20 FALSE FALSE
## 3 542 33 FALSE FALSE
## 4 544 -18 FALSE TRUE
## 5 554 -25 FALSE FALSE
## 6 554 12 FALSE TRUE
## 7 555 19 FALSE TRUE
## 8 557 -14 FALSE TRUE
## 9 557 -8 FALSE TRUE
## 10 558 8 FALSE TRUE
## # … with 336,766 more rows
Usando los resultados anteriores, ahora filtramos para obtener solos los vuelos que cumplan la condición anteriormente establecida.
#
flights %>%
mutate(
daytime = dep_time > 600 & dep_time < 2000,
ontime = abs(arr_delay) < 20,
.keep = "used"
) %>%
filter(daytime & ontime)## # A tibble: 172,286 × 4
## dep_time arr_delay daytime ontime
## <int> <dbl> <lgl> <lgl>
## 1 601 -6 TRUE TRUE
## 2 602 -8 TRUE TRUE
## 3 602 16 TRUE TRUE
## 4 606 -12 TRUE TRUE
## 5 606 -8 TRUE TRUE
## 6 607 -17 TRUE TRUE
## 7 611 14 TRUE TRUE
## 8 613 4 TRUE TRUE
## 9 615 -9 TRUE TRUE
## 10 622 3 TRUE TRUE
## # … with 172,276 more rows
# obtenemos 172.286 filaslibrary(visdat)
library(naniar)# cambiar de nombre el dataframe flights
vuelos <- flights
# crear un subconjunto
vuelos <- vuelos[1:100000,]
vis_dat(vuelos, warn_large_data = FALSE)vis_miss(vuelos, sort_miss = TRUE, warn_large_data = FALSE)vuelos %>% count(dest, sort = TRUE)## # A tibble: 101 × 2
## dest n
## <chr> <int>
## 1 ATL 5109
## 2 ORD 5035
## 3 LAX 4742
## 4 BOS 4631
## 5 CLT 4254
## 6 MCO 4099
## 7 SFO 3979
## 8 FLL 3620
## 9 MIA 3571
## 10 DCA 2854
## # … with 91 more rows
Agrupación manual.
vuelos %>%
group_by(dest) %>%
summarise(
n = n(), delay = mean(arr_delay, na.rm = TRUE)
)## # A tibble: 101 × 3
## dest n delay
## <chr> <int> <dbl>
## 1 ABQ 79 7.11
## 2 ACK 23 -0.870
## 3 ALB 144 26.5
## 4 ATL 5109 6.72
## 5 AUS 679 1.81
## 6 AVL 79 11.5
## 7 BDL 78 11.8
## 8 BGR 149 6.10
## 9 BHM 76 15.2
## 10 BNA 1875 9.43
## # … with 91 more rows
donde n() es una función especial de resumen y que toma la información de grupo activo. SOlo funciona dentro agrupaciones dplyr.
Busquemos los aeropuertos mas utilizados por destino.
vuelos %>%
group_by(dest) %>%
summarise(
carriers = n_distinct(carrier)
) %>%
arrange(desc(carriers))## # A tibble: 101 × 2
## dest carriers
## <chr> <int>
## 1 ATL 7
## 2 BOS 7
## 3 CLT 6
## 4 DCA 6
## 5 MSP 6
## 6 MSY 6
## 7 ORD 6
## 8 TPA 6
## 9 AUS 5
## 10 BNA 5
## # … with 91 more rows
vuelos %>%
filter(dep_delay < 120) |>
ggplot(aes(dep_delay)) +
geom_histogram(binwidth = 5)# carga de librerias
library(ggthemes)
#
dataset <- read.csv("titanic3.csv")
str(dataset)## 'data.frame': 1309 obs. of 14 variables:
## $ pclass : int 1 1 1 1 1 1 1 1 1 1 ...
## $ survived : int 1 1 0 0 0 1 1 0 1 0 ...
## $ name : chr "Allen, Miss. Elisabeth Walton" "Allison, Master. Hudson Trevor" "Allison, Miss. Helen Loraine" "Allison, Mr. Hudson Joshua Creighton" ...
## $ sex : chr "female" "male" "female" "male" ...
## $ age : num 29 0.917 2 30 25 ...
## $ sibsp : int 0 1 1 1 1 0 1 0 2 0 ...
## $ parch : int 0 2 2 2 2 0 0 0 0 0 ...
## $ ticket : chr "24160" "113781" "113781" "113781" ...
## $ fare : num 211 152 152 152 152 ...
## $ cabin : chr "B5" "C22 C26" "C22 C26" "C22 C26" ...
## $ embarked : chr "S" "S" "S" "S" ...
## $ boat : chr "2" "11" "" "" ...
## $ body : int NA NA NA 135 NA NA NA NA NA 22 ...
## $ home.dest: chr "St Louis, MO" "Montreal, PQ / Chesterville, ON" "Montreal, PQ / Chesterville, ON" "Montreal, PQ / Chesterville, ON" ...
titanic <- dataset %>%
mutate(survived=ifelse(survived==1,"Survived","Dead")) %>%
mutate(survived = as.factor(survived),
pclass=as.factor(pclass),
sex=as.factor(sex),
embarked=as.factor(embarked))
glimpse(titanic)## Rows: 1,309
## Columns: 14
## $ pclass <fct> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, …
## $ survived <fct> Survived, Survived, Dead, Dead, Dead, Survived, Survived, De…
## $ name <chr> "Allen, Miss. Elisabeth Walton", "Allison, Master. Hudson Tr…
## $ sex <fct> female, male, female, male, female, male, female, male, fema…
## $ age <dbl> 29.0000, 0.9167, 2.0000, 30.0000, 25.0000, 48.0000, 63.0000,…
## $ sibsp <int> 0, 1, 1, 1, 1, 0, 1, 0, 2, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, …
## $ parch <int> 0, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, …
## $ ticket <chr> "24160", "113781", "113781", "113781", "113781", "19952", "1…
## $ fare <dbl> 211.3375, 151.5500, 151.5500, 151.5500, 151.5500, 26.5500, 7…
## $ cabin <chr> "B5", "C22 C26", "C22 C26", "C22 C26", "C22 C26", "E12", "D7…
## $ embarked <fct> S, S, S, S, S, S, S, S, S, C, C, C, C, S, S, S, C, C, C, C, …
## $ boat <chr> "2", "11", "", "", "", "3", "10", "", "D", "", "", "4", "9",…
## $ body <int> NA, NA, NA, 135, NA, NA, NA, NA, NA, 22, 124, NA, NA, NA, NA…
## $ home.dest <chr> "St Louis, MO", "Montreal, PQ / Chesterville, ON", "Montreal…
Fueron los niños priorizados frente a los adultos?
ggplot(titanic[], aes(x=age, fill=survived, color=survived)) + ggthemes::theme_economist() + scale_color_gdocs() + ggthemes::scale_fill_gdocs()+ geom_histogram(aes(y=..density..), color="grey17") +
geom_density(alpha=.2, fill="yellow") +
theme(legend.position = "top")ggplot(titanic[], aes(x=fare, fill=survived, color=survived)) + ggthemes::theme_economist() + scale_color_gdocs() + ggthemes::scale_fill_gdocs()+ geom_histogram(aes(y=..density..), color="grey17") +
geom_density(alpha=.2, fill="yellow") +
theme(legend.position = "right")