In this lab we explore flights, specifically a random sample of domestic flights that departed from the three major New York City airports in 2013.

We will generate simple graphical and numerical summaries of data on these flights and explore delay times. You can find the instructions for this lab here.

# 1. load the library "tidyverse"

library(tidyverse)

# 2. use the read_csv file to read the dataset

nycflights <- read_csv("data/nycflights.csv")

Exercise 1

Question: Experiment with different binwidths to adjust your histogram in a way that will show its important features. You may also want to try using the + scale_x_log10() . What features are revealed now that were obscured in the original histogram? Note: When using the log scale, you may need to experiment with bin widths that are smaller than 1, such as binwidth=0.1 or even less!

# Write your code to create a histogram of delays

ggplot(data = nycflights, aes(x = dep_delay)) + 
  geom_histogram(binwidth = 15)

ggplot(data = nycflights, aes(x = dep_delay)) + 
  geom_histogram(binwidth = 150)

ggplot(data = nycflights, aes(x = dep_delay)) +
 geom_histogram(binwidth = 0.1) +
 scale_x_log10()
## Warning in self$trans$transform(x): NaNs produced
## Warning: Transformation introduced infinite values in continuous x-axis
## Warning: Removed 19936 rows containing non-finite values (`stat_bin()`).

Answer: [Thanks to the logarithmic scale, the skewedness of the data to the right can be seen. ]

Exercise 2

Question: Create a new data frame that includes flights headed to SFO in February, and save this data frame as sfo_feb_flights. How many flights meet these criteria? Try using the function nrow() inside of inline code in your answer, and knit your file to see that your text shows the answer correctly.

# Insert code for Exercise 2 here


sfo_feb_flights <- nycflights %>%
  filter(dest == "SFO", month == 2)
  num_flights <- nrow(sfo_feb_flights)

Answer: [There were a total of r nrow(sfo_feb_flights) from New York to San-Francisco in February of 2013.]

Exercise 3

Question: Describe the distribution of the arrival delays of flights headed to SFO in February, using an appropriate histogram and summary statistics. Hint: The summary statistics you use should depend on the shape of the distribution.

# Insert code for Exercise 3 here

sfo_feb_flights %>%
  ggplot(aes(arr_delay), col="pink", fill="pink") +
  geom_histogram(binwidth =3, col="pink", fill="pink")

Answer: [The distribution is skewed to the right, so we should use the median r median(sfo_feb_flights\(arr_delay) and the IQR r IQR(sfo_feb_flights\)arr_delay) to represent the distribution we can see that 50% arrive ahead of schedule because they leave 11 mins earlier or more than the scheduled time.]

Exercise 4

Question: Calculate the median and interquartile range for arr_delays of flights in in the sfo_feb_flights data frame, grouped by carrier. Which carrier has the most variable arrival delays?

# Insert code for the Exercise here


sfo_feb_flights %>%
  group_by(carrier) %>%
  summarise(md.delay = median(arr_delay), iqr.delay = IQR(arr_delay))

Answer: [AA has the highest median of delays being 5.0. The most variable delays can be observed by UA and DL with an IQR of of 22.00.]

Exercise 5

Question: Create a list of origin airports and their rate of on-time-departure. Then visualize the distribution of on-time-departure rate across the three airports using a segmented bar plot (see below). If you could select an airport based on on time departure percentage, which NYC airport would you choose to fly out of? Hint: For the segmented bar plot, will need to map the aesthetic arguments as follows: x = origin, fill = dep_type and a geom_bar() layer. Create three plots, one with geom_bar() layer, one with geom_bar(position = "fill") and the third with geom_bar(position = "dodge"). Explain the difference between the three results.

# Insert code for the Exercise here

nycflights <- nycflights %>%
  mutate(dep_type = ifelse (dep_delay < 5, "on time", "delayed"))

nycflights %>%
  group_by(origin) %>%
  summarise(on_time_dep_rate = sum(dep_type == "on time") / n()) %>%
  arrange(desc(on_time_dep_rate))
nycflights %>%
  ggplot(aes(x = origin, fill = dep_type)) +
  geom_bar(position = "fill") +
  labs (y="proportion")

Answer: [We would chose to fly out with LGA as the on time percentage is 73%, whereas JFK shows a 69% of flights departing on time and lastly EWR as leaving with 64% on time]

Exercise 6

Question: Mutate the data frame so that it includes a new variable that contains the average speed, avg_speed traveled by the plane for each flight (in mph, or if you are brave, in km/h). Now make a scatterplot of avg_speed vs. distance. Describe the relationship between average speed and distance. Hint: Average speed can be calculated as distance divided by number of hours of travel, and note that air_time is given in minutes. You will need to use geom_point(). Think carefully which of the two variables is the predictor (on the x-axis) and which is the outcome variable (on the y-axis) and explain why you made this choice. Describe the relationship between average speed and distance.

# Insert code for the Exercise here

nycflights <- nycflights %>%
  mutate(distance_km = distance * 1.6,
         air_time_h = air_time / 60,
         speed = distance_km / air_time_h)

nycflights %>%
  ggplot(aes(x = log(distance_km), y = log(speed))) + 
  geom_point() +
  geom_smooth() +
  scale_x_continuous(labels = scales::comma_format()) +  
  labs(x = "Logarithm of Distance (log_km)", y = "Logarithm of Average Speed")  # Adding labels
## `geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'

Answer: [For longer distances, the flights tend to achieve higher average speeds]

Exercise 7

Question: Replicate the following plot and determine what is the cutoff point for the latest departure delay where you can still have a chance to arrive at your destination on time. Hint: The data frame plotted only contains flights from American Airlines, Delta Airlines, and United Airlines, and the points are colored by carrier. To determine the cut off point, try scaling the x-axis and the y-axis on the logarithmic scale. You can also filter the data, so that you plot only data where arr_delay <= 0.

# Insert code for the Exercise here

nycflights %>%
  filter(carrier %in% c("AA", "DL", "UA")) %>%
  filter(arr_delay <= 0) %>%
  ggplot(aes(x=dep_delay, y=arr_delay, color=carrier)) +
  geom_jitter(size = .5, alpha = .5) +
  scale_x_continuous(breaks = seq(-20, 100, 5))

Answer: [DL had the largest departure delay with 63 mins and arriving on time at destination.]