#Instalar librerias
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.1.0 ✔ readr 2.1.4
## ✔ forcats 1.0.0 ✔ stringr 1.5.0
## ✔ ggplot2 3.4.1 ✔ tibble 3.1.8
## ✔ lubridate 1.9.2 ✔ tidyr 1.3.0
## ✔ purrr 1.0.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## ℹ Use the ]8;;http://conflicted.r-lib.org/conflicted package]8;; to force all conflicts to become errors
library(dplyr)
library(nycflights13)
library(ggplot2)
#Consulta y explora el data frame planes y weather para que conozcas su contenido.
view(planes)
view(weather)
view(airlines)
view(airports)
#Se necesita saber de cada vuelo, la aerolínea, el aeropuerto de origen y el aeropuerto destino
df= select(flights, flight, carrier, origin, dest)
#En la consulta anterior se necesita conocer el nombre de la aerolínea.
df2= df%>% left_join(airlines, by=c('carrier'))
df2
## # A tibble: 336,776 × 5
## flight carrier origin dest name
## <int> <chr> <chr> <chr> <chr>
## 1 1545 UA EWR IAH United Air Lines Inc.
## 2 1714 UA LGA IAH United Air Lines Inc.
## 3 1141 AA JFK MIA American Airlines Inc.
## 4 725 B6 JFK BQN JetBlue Airways
## 5 461 DL LGA ATL Delta Air Lines Inc.
## 6 1696 UA EWR ORD United Air Lines Inc.
## 7 507 B6 EWR FLL JetBlue Airways
## 8 5708 EV LGA IAD ExpressJet Airlines Inc.
## 9 79 B6 JFK MCO JetBlue Airways
## 10 301 AA LGA ORD American Airlines Inc.
## # … with 336,766 more rows
#Se necesita saber la cantidad de vuelos por cada destino para identificar cuáles son los destinos más buscados. select y count
df3 = group_by(flights, dest) %>% summarise(count = n()) %>% arrange(desc(count))
df3
## # A tibble: 105 × 2
## dest count
## <chr> <int>
## 1 ORD 17283
## 2 ATL 17215
## 3 LAX 16174
## 4 BOS 15508
## 5 MCO 14082
## 6 CLT 14064
## 7 SFO 13331
## 8 FLL 12055
## 9 MIA 11728
## 10 DCA 9705
## # … with 95 more rows
#Se necesita conocer las aerolíneas (clave y nombre) y destinos que vuelan por la Mañana: de 6 a 12, Tarde: de 12 a 19 , Noche: de 19 a 24 y Madrugada de 24 a 6.
# Agrega un nuevo campo a la tabla con el nombre de clas_horario y agrega, mañana, tarde, noche y madrugada según sea el caso. dep_time
df4 <- select(flights, dest, carrier, dep_time) %>% left_join(airlines, by=c('carrier')) %>% mutate(class_horario = ifelse (dep_time <= 600, 'madrugada', ifelse(dep_time <= 1200, 'mañana', ifelse(dep_time <= 1900, 'tarde', ifelse(dep_time <= 2400,'noche' )))))
df4
## # A tibble: 336,776 × 5
## dest carrier dep_time name class_horario
## <chr> <chr> <int> <chr> <chr>
## 1 IAH UA 517 United Air Lines Inc. madrugada
## 2 IAH UA 533 United Air Lines Inc. madrugada
## 3 MIA AA 542 American Airlines Inc. madrugada
## 4 BQN B6 544 JetBlue Airways madrugada
## 5 ATL DL 554 Delta Air Lines Inc. madrugada
## 6 ORD UA 554 United Air Lines Inc. madrugada
## 7 FLL B6 555 JetBlue Airways madrugada
## 8 IAD EV 557 ExpressJet Airlines Inc. madrugada
## 9 MCO B6 557 JetBlue Airways madrugada
## 10 ORD AA 558 American Airlines Inc. madrugada
## # … with 336,766 more rows
# Se necesita saber la cantidad de vuelos por aerolínea y destino que hay por la Mañana, Tarde, Noche y Madrugada.
df5 <- group_by(df4,carrier, dest, class_horario) %>% count(class_horario, name = 'Numero_vuelos') %>% arrange(desc(Numero_vuelos))
df5
## # A tibble: 1,192 × 4
## # Groups: carrier, dest, class_horario [1,192]
## carrier dest class_horario Numero_vuelos
## <chr> <chr> <chr> <int>
## 1 DL ATL tarde 4766
## 2 US CLT mañana 4389
## 3 DL ATL mañana 4294
## 4 AA DFW tarde 3675
## 5 US CLT tarde 3540
## 6 AA MIA mañana 3165
## 7 UA ORD tarde 3101
## 8 AA MIA tarde 3050
## 9 UA SFO tarde 2987
## 10 UA IAH tarde 2848
## # … with 1,182 more rows
#Se necesita saber a qué destinos vuela la aerolínea American Airlines Inc.-AA durante la madrugada.
df6 <- df5 %>% filter(carrier%in%("AA") & class_horario == 'madrugada')
df6
## # A tibble: 4 × 4
## # Groups: carrier, dest, class_horario [4]
## carrier dest class_horario Numero_vuelos
## <chr> <chr> <chr> <int>
## 1 AA MIA madrugada 546
## 2 AA DFW madrugada 241
## 3 AA ORD madrugada 207
## 4 AA LAX madrugada 11
#¿Qué aviones utiliza la aerolínea AA? aerolínea, tipo, motor y número de asientos y ¿Cuántos vuelos se han realizado con cada uno? elimina los NA's
df7 <- planes %>% left_join(flights, by=c('tailnum')) %>% select(carrier,type, engine, seats) %>% filter(carrier %in% ('AA'))
## Warning in left_join(., flights, by = c("tailnum")): Each row in `x` is expected to match at most 1 row in `y`.
## ℹ Row 1 of `x` matches multiple rows.
## ℹ If multiple matches are expected, set `multiple = "all"` to silence this
## warning.
df7
## # A tibble: 10,171 × 4
## carrier type engine seats
## <chr> <chr> <chr> <int>
## 1 AA Fixed wing single engine Reciprocating 2
## 2 AA Fixed wing single engine Reciprocating 2
## 3 AA Fixed wing single engine Reciprocating 2
## 4 AA Fixed wing single engine Reciprocating 2
## 5 AA Fixed wing single engine Reciprocating 2
## 6 AA Fixed wing single engine Reciprocating 2
## 7 AA Fixed wing single engine Reciprocating 2
## 8 AA Fixed wing single engine Reciprocating 2
## 9 AA Fixed wing single engine Reciprocating 2
## 10 AA Fixed wing single engine Reciprocating 2
## # … with 10,161 more rows
df8 <- df7 %>% group_by(type) %>% count(name = 'Total')
df8
## # A tibble: 3 × 2
## # Groups: type [3]
## type Total
## <chr> <int>
## 1 Fixed wing multi engine 9318
## 2 Fixed wing single engine 729
## 3 Rotorcraft 124
#VISUALIZACIÓN DE DATOS
#Se solicita analizar para la aerolínea American Airlines si los vuelos que tienen retraso en la partida también tienen retraso en la hora de llegada.Gráfica Scatterplot.
df9 <- filter(flights, carrier%in%("AA"))
df9
## # A tibble: 32,729 × 19
## year month day dep_time sched_de…¹ dep_d…² arr_t…³ sched…⁴ arr_d…⁵ carrier
## <int> <int> <int> <int> <int> <dbl> <int> <int> <dbl> <chr>
## 1 2013 1 1 542 540 2 923 850 33 AA
## 2 2013 1 1 558 600 -2 753 745 8 AA
## 3 2013 1 1 559 600 -1 941 910 31 AA
## 4 2013 1 1 606 610 -4 858 910 -12 AA
## 5 2013 1 1 623 610 13 920 915 5 AA
## 6 2013 1 1 628 630 -2 1137 1140 -3 AA
## 7 2013 1 1 629 630 -1 824 810 14 AA
## 8 2013 1 1 635 635 0 1028 940 48 AA
## 9 2013 1 1 656 700 -4 854 850 4 AA
## 10 2013 1 1 656 659 -3 949 959 -10 AA
## # … with 32,719 more rows, 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
scatterplot <- ggplot(df9, aes(x=dep_delay, y=arr_delay)) +
geom_point(size = .5, color='orange') +
geom_smooth(method = lm) +
labs(title='Restraso American Airlines', x= 'Retraso partida', y='Retraso llegada')
scatterplot
## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 782 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 782 rows containing missing values (`geom_point()`).

#Visualiza la tendencia de la temperatura durante los primeros 15 días del mes de Enero en los vuelos que parten del aeropuerto “Newark, EWR”, utilizar una gráfica de línea.
df10 <- select(weather, origin, month, day, time_hour, temp) %>% filter(origin%in%("EWR") & month%in%(1) & day%in%(1:15))
df10
## # A tibble: 358 × 5
## origin month day time_hour temp
## <chr> <int> <int> <dttm> <dbl>
## 1 EWR 1 1 2013-01-01 01:00:00 39.0
## 2 EWR 1 1 2013-01-01 02:00:00 39.0
## 3 EWR 1 1 2013-01-01 03:00:00 39.0
## 4 EWR 1 1 2013-01-01 04:00:00 39.9
## 5 EWR 1 1 2013-01-01 05:00:00 39.0
## 6 EWR 1 1 2013-01-01 06:00:00 37.9
## 7 EWR 1 1 2013-01-01 07:00:00 39.0
## 8 EWR 1 1 2013-01-01 08:00:00 39.9
## 9 EWR 1 1 2013-01-01 09:00:00 39.9
## 10 EWR 1 1 2013-01-01 10:00:00 41
## # … with 348 more rows
line_plot <- ggplot(df10, aes(x=time_hour, y=temp)) +
geom_line(color="#69b3a2", size=0.8, alpha=0.9) +
labs(title='Tendencia de temperadura (Enero 1- 15)', x= 'Dia', y='Temperatura')
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
line_plot

#Visualiza la temperatura más frecuente en los primeros 15 días del mes de Enero, utilizar un histrograma.
histogram <- ggplot(df10, aes(x=temp)) +
geom_histogram(color= 'white' , fill="#E69F00") +
labs(title='Frecuencia de temperatura (Enero 1- 15)', x= 'Temperatura', y='Frecuencia')
histogram
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

#Utiliza Facets para observar cómo varía la temperatura en cada mes en él histograma del punto anterior . (Punto anterior solo tiene enero, se hara por todo el año)
histogram_2 <- ggplot(weather, aes(x=temp)) +
geom_histogram(color= 'white' , fill="#E69F00") +
labs(title='Frecuencia de temperatura (Enero 1- 15)', x= 'Temperatura', y='Frecuencia') +
facet_wrap(. ~ month, ncol=2)
histogram_2
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 1 rows containing non-finite values (`stat_bin()`).

#Número de vuelos que salieron de Nueva York en 2013 por aerolínea (mostrar solamente las 10 aerolíneas con más vuelos), utilizar gráfica de barras.
df11 <- flights %>% group_by(carrier) %>% count() %>% arrange(desc(n)) %>% head(10)
df11
## # A tibble: 10 × 2
## # Groups: carrier [10]
## carrier n
## <chr> <int>
## 1 UA 58665
## 2 B6 54635
## 3 EV 54173
## 4 DL 48110
## 5 AA 32729
## 6 MQ 26397
## 7 US 20536
## 8 9E 18460
## 9 WN 12275
## 10 VX 5162
bar_graph <- ggplot(df11, aes(x=carrier, y=n)) +
geom_bar(width = 0.8, stat='identity', fill='pink') +
labs(title='Vuelos por aerolinea - Nueva York 2013', x= 'Aerolinea', y='Vuelos') +
geom_text(aes(label=n), vjust=1.6, color="white", size=3.5)
bar_graph

#Visualiza el punto anterior en una gráfica de pie.
piechart <- ggplot(df11, aes(x='', y=n, fill=carrier)) +
geom_bar(stat="identity", width=1, color='white') +
coord_polar("y", start=0) +
theme_void() +
labs(title='Vuelos por aerolinea - Nueva York 2013')
piechart

#Relaciona el data frame fligths con el data frame airports a través del campo destino ¿cómo lograr estas relación?
df12 <- airports %>% rename('dest' = 'faa')
df13 <- flights %>% left_join(df12, by=c('dest'))
df13
## # A tibble: 336,776 × 26
## year month day dep_time sched_de…¹ 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
## 7 2013 1 1 555 600 -5 913 854 19 B6
## 8 2013 1 1 557 600 -3 709 723 -14 EV
## 9 2013 1 1 557 600 -3 838 846 -8 B6
## 10 2013 1 1 558 600 -2 753 745 8 AA
## # … with 336,766 more rows, 16 more variables: flight <int>, tailnum <chr>,
## # origin <chr>, dest <chr>, air_time <dbl>, distance <dbl>, hour <dbl>,
## # minute <dbl>, time_hour <dttm>, name <chr>, lat <dbl>, lon <dbl>,
## # alt <dbl>, tz <dbl>, dst <chr>, tzone <chr>, and abbreviated variable names
## # ¹sched_dep_time, ²dep_delay, ³arr_time, ⁴sched_arr_time, ⁵arr_delay
#Crea un nuevo data frame con el punto anterior únicamente con los 5 carriers con más vuelos por origen
df14 <- df13 %>% select(carrier, origin) %>% group_by(origin, carrier) %>% count(origin) %>% arrange(desc(n))
df14
## # A tibble: 35 × 3
## # Groups: origin, carrier [35]
## origin carrier n
## <chr> <chr> <int>
## 1 EWR UA 46087
## 2 EWR EV 43939
## 3 JFK B6 42076
## 4 LGA DL 23067
## 5 JFK DL 20701
## 6 LGA MQ 16928
## 7 LGA AA 15459
## 8 JFK 9E 14651
## 9 JFK AA 13783
## 10 LGA US 13136
## # … with 25 more rows
top_EWR = df14 %>% filter(origin%in%("EWR")) %>% head(5)
top_EWR
## # A tibble: 5 × 3
## # Groups: origin, carrier [5]
## origin carrier n
## <chr> <chr> <int>
## 1 EWR UA 46087
## 2 EWR EV 43939
## 3 EWR B6 6557
## 4 EWR WN 6188
## 5 EWR US 4405
top_LGA <- df14 %>% filter(origin%in%("LGA")) %>% head(5)
top_LGA
## # A tibble: 5 × 3
## # Groups: origin, carrier [5]
## origin carrier n
## <chr> <chr> <int>
## 1 LGA DL 23067
## 2 LGA MQ 16928
## 3 LGA AA 15459
## 4 LGA US 13136
## 5 LGA EV 8826
top_JFK <- df14 %>% filter(origin%in%("JFK")) %>% head(5)
top_JFK
## # A tibble: 5 × 3
## # Groups: origin, carrier [5]
## origin carrier n
## <chr> <chr> <int>
## 1 JFK B6 42076
## 2 JFK DL 20701
## 3 JFK 9E 14651
## 4 JFK AA 13783
## 5 JFK MQ 7193
df16 <- merge(x=top_EWR, y=top_LGA, by=c('origin', 'carrier', 'n'), all=TRUE)
df16
## origin carrier n
## 1 EWR B6 6557
## 2 EWR EV 43939
## 3 EWR UA 46087
## 4 EWR US 4405
## 5 EWR WN 6188
## 6 LGA AA 15459
## 7 LGA DL 23067
## 8 LGA EV 8826
## 9 LGA MQ 16928
## 10 LGA US 13136
df17 <- merge(x=df16, y=top_JFK, by=c('origin', 'carrier', 'n'), all=TRUE)
df17
## origin carrier n
## 1 EWR B6 6557
## 2 EWR EV 43939
## 3 EWR UA 46087
## 4 EWR US 4405
## 5 EWR WN 6188
## 6 JFK 9E 14651
## 7 JFK AA 13783
## 8 JFK B6 42076
## 9 JFK DL 20701
## 10 JFK MQ 7193
## 11 LGA AA 15459
## 12 LGA DL 23067
## 13 LGA EV 8826
## 14 LGA MQ 16928
## 15 LGA US 13136
#Realiza una visualización del punto anterior de las siguientes tres formas.
graph_1 <- ggplot(df17, aes(x=carrier, y=n, fill=origin))+
geom_bar(stat="identity", color='white') +
theme_minimal() +
scale_fill_manual(values=c('#999999','#E69F00', 'pink')) +
labs(title='Top 5 aerolineas por origen', x='Aerolinea', y='Cantidad')
graph_1

graph_2 <- ggplot(df17, aes(x=carrier, y=n, fill=origin))+
geom_bar(stat="identity", color='white' ,position=position_dodge()) +
theme_minimal() +
scale_fill_manual(values=c('#999999','#E69F00', 'pink')) +
labs(title='Top 5 aerolineas por origen', x='Aerolinea', y='Cantidad')
graph_2

graph_3 <- ggplot(df17, aes(x=carrier, y=n, fill=origin))+
geom_bar(stat="identity", color='white' ,position=position_dodge()) +
theme_minimal() +
scale_fill_manual(values=c('#999999','#E69F00', 'pink')) +
labs(title='Top 5 aerolineas por origen', x='Aerolinea', y='Cantidad') +
facet_wrap(. ~ origin, ncol=1)
graph_3
