Introduction to data

Complete all **Exercises**, and submit answers to **Questions** on the Coursera platform.

Some define statistics as the field that focuses on turning information into knowledge. The first step in that process is to summarize and describe the raw information - the data. In this lab we explore flights, specifically a random sample of domestic flights that departed from the three major New York City airport in 2013. We will generate simple graphical and numerical summaries of data on these flights and explore delay times. As this is a large data set, along the way you'll also learn the indispensable skills of data processing and subsetting.

Getting started

Load packages

In this lab we will explore the data using the dplyr package and visualize it using the ggplot2 package for data visualization. The data can be found in the companion package for this course, statsr.

Let's load the packages.


In [1]:
library(statsr)
library(dplyr)
library(ggplot2)


Attaching package: ‘dplyr’

The following objects are masked from ‘package:stats’:

    filter, lag

The following objects are masked from ‘package:base’:

    intersect, setdiff, setequal, union

Warning message:
: package ‘ggplot2’ was built under R version 3.2.4

Data

The Bureau of Transportation Statistics (BTS) is a statistical agency that is a part of the Research and Innovative Technology Administration (RITA). As its name implies, BTS collects and makes available transportation data, such as the flights data we will be working with in this lab.

We begin by loading the nycflights data frame. Type the following in your console to load the data:


In [2]:
data(nycflights)

The data frame containing 32735 flights that shows up in your workspace is a data matrix, with each row representing an observation and each column representing a variable. R calls this data format a data frame, which is a term that will be used throughout the labs.

To view the names of the variables, type the command


In [3]:
names(nycflights)


Out[3]:
  1. 'year'
  2. 'month'
  3. 'day'
  4. 'dep_time'
  5. 'dep_delay'
  6. 'arr_time'
  7. 'arr_delay'
  8. 'carrier'
  9. 'tailnum'
  10. 'flight'
  11. 'origin'
  12. 'dest'
  13. 'air_time'
  14. 'distance'
  15. 'hour'
  16. 'minute'

In [4]:
str(nycflights)


Classes ‘tbl_df’ and 'data.frame':	32735 obs. of  16 variables:
 $ year     : int  2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 ...
 $ month    : int  6 5 12 5 7 1 12 8 9 4 ...
 $ day      : int  30 7 8 14 21 1 9 13 26 30 ...
 $ dep_time : int  940 1657 859 1841 1102 1817 1259 1920 725 1323 ...
 $ dep_delay: num  15 -3 -1 -4 -3 -3 14 85 -10 62 ...
 $ arr_time : int  1216 2104 1238 2122 1230 2008 1617 2032 1027 1549 ...
 $ arr_delay: num  -4 10 11 -34 -8 3 22 71 -8 60 ...
 $ carrier  : chr  "VX" "DL" "DL" "DL" ...
 $ tailnum  : chr  "N626VA" "N3760C" "N712TW" "N914DL" ...
 $ flight   : int  407 329 422 2391 3652 353 1428 1407 2279 4162 ...
 $ origin   : chr  "JFK" "JFK" "JFK" "JFK" ...
 $ dest     : chr  "LAX" "SJU" "LAX" "TPA" ...
 $ air_time : num  313 216 376 135 50 138 240 48 148 110 ...
 $ distance : num  2475 1598 2475 1005 296 ...
 $ hour     : num  9 16 8 18 11 18 12 19 7 13 ...
 $ minute   : num  40 57 59 41 2 17 59 20 25 23 ...

This returns the names of the variables in this data frame. The codebook (description of the variables) is included below. This information can also be found in the help file for the data frame which can be accessed by typing ?nycflights in the console.

  • year, month, day: Date of departure
  • dep_time, arr_time: Departure and arrival times, local timezone.
  • dep_delay, arr_delay: Departure and arrival delays, in minutes. Negative times represent early departures/arrivals.
  • carrier: Two letter carrier abbreviation.
    • 9E: Endeavor Air Inc.
    • AA: American Airlines Inc.
    • AS: Alaska Airlines Inc.
    • B6: JetBlue Airways
    • DL: Delta Air Lines Inc.
    • EV: ExpressJet Airlines Inc.
    • F9: Frontier Airlines Inc.
    • FL: AirTran Airways Corporation
    • HA: Hawaiian Airlines Inc.
    • MQ: Envoy Air
    • OO: SkyWest Airlines Inc.
    • UA: United Air Lines Inc.
    • US: US Airways Inc.
    • VX: Virgin America
    • WN: Southwest Airlines Co.
    • YV: Mesa Airlines Inc.
  • tailnum: Plane tail number
  • flight: Flight number
  • origin, dest: Airport codes for origin and destination. (Google can help you with what code stands for which airport.)
  • air_time: Amount of time spent in the air, in minutes.
  • distance: Distance flown, in miles.
  • hour, minute: Time of departure broken in to hour and minutes.

A very useful function for taking a quick peek at your data frame, and viewing its dimensions and data types is str, which stands for structure.

The nycflights data frame is a massive trove of information. Let’s think about some questions we might want to answer with these data:

We might want to find out how delayed flights headed to a particular destination tend to be. We might want to evaluate how departure delays vary over months. Or we might want to determine which of the three major NYC airports has a better on time percentage for departing flights.

Seven verbs

The dplyr package offers seven verbs (functions) for basic data manipulation:

  • filter()
  • arrange()
  • select()
  • distinct()
  • mutate()
  • summarise()
  • sample_n()

We will use some of these functions in this lab, and learn about others in a future lab.

Analysis

Departure delays in flights to Raleigh-Durham (RDU)

We can examine the distribution of departure delays of all flights with a histogram.


In [5]:
ggplot(data = nycflights, aes(x = dep_delay)) +
  geom_histogram()


`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

This function says to plot the dep_delay variable from the nycflights data frame on the x-axis. It also defines a geom (short for geometric object), which describes the type of plot you will produce.

Histograms are generally a very good way to see the shape of a single distribution, but that shape can change depending on how the data is split between the different bins. You can easily define the binwidth you want to use:


In [6]:
ggplot(data = nycflights, aes(x = dep_delay)) +
  geom_histogram(binwidth = 15)



In [7]:
ggplot(data = nycflights, aes(x = dep_delay)) +
  geom_histogram(binwidth = 150)


Exercise

How do these three histograms with the various binwidths compare?

If we want to focus on departure delays of flights headed to RDU only, we need to first filter the data for flights headed to RDU (dest == "RDU") and then make a histogram of only departure delays of only those flights.


In [8]:
rdu_flights <- nycflights %>%
  filter(dest == "RDU")
ggplot(data = rdu_flights, aes(x = dep_delay)) +
  geom_histogram()


`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Let's decipher these three lines of code:

  • Line 1: Take the nycflights data frame, filter for flights headed to RDU, and save the result as a new data frame called rdu_flights.
    • == means "if it's equal to".
    • RDU is in quotation marks since it is a character string.
  • Line 2: Basically the same ggplot call from earlier for making a histogram, except that it uses the data frame for flights headed to RDU instead of all flights.

Logical operators:

Filtering for certain observations (e.g. flights from a particular airport) is often of interest in data frames where we might want to examine observations with certain characteristics separately from the rest of the data. To do so we use the filter function and a series of logical operators. The most commonly used logical operators for data analysis are as follows:

  • == means "equal to"
  • != means "not equal to"
  • > or < means "greater than" or "less than"
  • >= or <= means "greater than or equal to" or "less than or equal to"

We can also obtain numerical summaries for these flights:


In [12]:
rdu_flights %>%
  summarise(mean_dd = mean(dep_delay), sd_dd = sd(dep_delay), n = n())


Out[12]:
mean_ddsd_ddn
111.6991335.55567801

Note that in the summarise function we created a list of two elements. The names of these elements are user defined, like mean_dd, sd_dd, n, and you could customize these names as you like (just don't use spaces in your names). Calculating these summary statistics also require that you know the function calls. Note that n() reports the sample size.

Summary statistics:

Some useful function calls for summary statistics for a single numerical variable are as follows:

  • mean
  • median
  • sd
  • var
  • IQR
  • range
  • min
  • max </div>

We can also filter based on multiple criteria. Suppose we are interested in flights headed to San Francisco (SFO) in February:


In [15]:
sfo_feb_flights <- nycflights %>%
  filter(dest == "SFO", month == 2)

Note that we can separate the conditions using commas if we want flights that are both headed to SFO and in February. If we are interested in either flights headed to SFO or in February we can use the | instead of the comma.

1. 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?

  1. 68
  2. 1345
  3. 2286
  4. 3563
  5. 32735

In [17]:
nrow(sfo_feb_flights)


Out[17]:
68

2. Make a histogram and calculate appropriate summary statistics for arrival delays of sfo_feb_flights. Which of the following is false?

  1. The distribution is unimodal.
  2. The distribution is right skewed.
  3. No flight is delayed more than 2 hours.
  4. The distribution has several extreme values on the right side.
  5. More than 50% of flights arrive on time or earlier than scheduled.

In [19]:
ggplot(data = sfo_feb_flights, aes(x = arr_delay)) +
  geom_histogram() # C is wrong, so choose 3


`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

In [ ]:

Another useful functionality is being able to quickly calculate summary statistics for various groups in your data frame. For example, we can modify the above command using the group_by function to get the same summary stats for each origin airport:


In [20]:
rdu_flights %>%
  group_by(origin) %>%
  summarise(mean_dd = mean(dep_delay), sd_dd = sd(dep_delay), n = n())


Out[20]:
originmean_ddsd_ddn
1EWR13.3655232.08492145
2JFK15.3966740.30535300
3LGA7.90449432.1862356

Here, we first grouped the data by origin, and then calculated the summary statistics.

3. Calculate the median and interquartile range for arr_delays of flights in the sfo_feb_flights data frame, grouped by carrier. Which carrier is the has the hights IQR of arrival delays?

  1. American Airlines
  2. JetBlue Airways
  3. Virgin America
  4. Delta and United Airlines
  5. Frontier Airlines

In [66]:
sfo_feb_flights %>%
    group_by(carrier) %>%
    summarise(median_dd = median(arr_delay), IQR_dd = IQR(arr_delay)) %>%
    arrange(desc(IQR_dd))
# Answer is AA


Out[66]:
carriermedian_ddIQR_dd
1DL-1522
2UA-1022
3VX-22.521.25
4AA517.5
5B6-10.512.25

Departure delays over months

Which month would you expect to have the highest average delay departing from an NYC airport?

Let's think about how we would answer this question:

  • First, calculate monthly averages for departure delays. With the new language we are learning, we need to
    • group_by months, then
    • summarise mean departure delays.
  • Then, we need to arrange these average delays in descending order

In [22]:
nycflights %>%
  group_by(month) %>%
  summarise(mean_dd = mean(dep_delay)) %>%
  arrange(desc(mean_dd))


Out[22]:
monthmean_dd
1720.75456
2620.35029
31217.36819
4414.55448
5313.5176
6513.2648
7812.6191
8210.68723
9110.23333
1096.872436
11116.103183
12105.880374

4. Which month has the highest average departure delay from an NYC airport?

  1. January
  2. March
  3. July
  4. October
  5. December

5. Which month has the highest median departure delay from an NYC airport?

  1. January
  2. March
  3. July
  4. October
  5. December

In [23]:
nycflights %>%
  group_by(month) %>%
  summarise(mean_dd = mean(dep_delay), median_dd = median(dep_delay)) %>%
  arrange(desc(median_dd)) # Month 12


Out[23]:
monthmean_ddmedian_dd
11217.368191
2620.350290
3720.754560
4313.5176-1
5513.2648-1
6812.6191-1
7110.23333-2
8210.68723-2
9414.55448-2
10116.103183-2
1196.872436-3
12105.880374-3

In [64]:
nycflights %>%
  group_by(month) %>%
  summarise(mean_dd = mean(dep_delay), IQR_dd = IQR(dep_delay)) %>%
  arrange(desc(IQR_dd)) # Month 12


Out[64]:
monthmean_ddIQR_dd
1720.7545626
2620.3502925
31217.3681925
4513.264819
5313.517617
6414.5544816
7210.6872315
8812.619115
9110.2333312
10116.10318310
11105.8803749
1296.8724368

6. Is the mean and the median a more reliable measure for deciding which month(s) to avoid flying if you really dislike delayed flights, and why?

  1. Mean would be more reliable as it gives us the true average.
  2. Mean would be more reliable as the distribution of delays is symmetric.
  3. Median would be more reliable as the distribution of delays is skewed.
  4. Median would be more reliable as the distribution of delays is symmetric.
  5. Both give us useful information.

C

We can also visualize the distributions of departure delays across months using side-by-side box plots:


In [28]:
ggplot(nycflights, aes(x = factor(month), y = dep_delay)) +
  geom_boxplot()


There is some new syntax here: We want departure delays on the y-axis and the months on the x-axis to produce side-by-side box plots. Side-by-side box plots require a categorical variable on the x-axis, however in the data frame month is stored as a numerical variable (numbers 1 - 12). Therefore we can force R to treat this variable as categorical, what R calls a factor, variable with factor(month).

On time departure rate for NYC airports

Suppose you will be flying out of NYC and want to know which of the three major NYC airports has the best on time departure rate of departing flights. Suppose also that for you a flight that is delayed for less than 5 minutes is basically "on time". You consider any flight delayed for 5 minutes of more to be "delayed".

In order to determine which airport has the best on time departure rate, we need to

  • first classify each flight as "on time" or "delayed",
  • then group flights by origin airport,
  • then calculate on time departure rates for each origin airport,
  • and finally arrange the airports in descending order for on time departure percentage.

Let's start with classifying each flight as "on time" or "delayed" by creating a new variable with the mutate function.


In [30]:
nycflights <- nycflights %>%
  mutate(dep_type = ifelse(dep_delay < 5, "on time", "delayed"))

The first argument in the mutate function is the name of the new variable we want to create, in this case dep_type. Then if dep_delay < 5 we classify the flight as "on time" and "delayed" if not, i.e. if the flight is delayed for 5 or more minutes.

Note that we are also overwriting the nycflights data frame with the new version of this data frame that includes the new dep_type variable.

We can handle all the remaining steps in one code chunk:


In [32]:
nycflights %>%
  group_by(origin) %>%
  summarise(ot_dep_rate = sum(dep_type == "on time") / n()) %>%
  arrange(desc(ot_dep_rate)) 
# Choose LGA


Out[32]:
originot_dep_rate
1LGA0.7279229
2JFK0.6935854
3EWR0.6369892

We can also visualize the distribution of on on time departure rate across the three airports using a segmented bar plot.


In [33]:
ggplot(data = nycflights, aes(x = origin, fill = dep_type)) +
  geom_bar()


8. 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). What is the tail number of the plane with the fastest avg_speed? Hint: Average speed can be calculated as distance divided by number of hours of travel, and note that air_time is given in minutes. If you just want to show the avg_speed and tailnum and none of the other variables, use the select function at the end of your pipe to select just these two variables with select(avg_speed, tailnum). You can Google this tail number to find out more about the aircraft.

  1. N666DN
  2. N755US
  3. N779JB
  4. N947UW
  5. N959UW

In [41]:
nycflights <- nycflights %>%
  mutate(avg_speed = distance / air_time * 60)

In [51]:
nycflights %>%
  #group_by(tailnum) %>%
  arrange(desc(avg_speed))  %>%
  select(avg_speed, tailnum)


Out[51]:
avg_speedtailnum
1703.384615384615N666DN
2557.441860465116N779JB
3554.219653179191N571JB
4547.885714285714N568JB
5547.885714285714N5EHAA
6547.885714285714N656JB
7544.772727272727N789JB
8538.651685393258N516JB
9535.642458100559N648JB
10535.642458100559N510JB
11533.038674033149N38268
12533.038674033149N53442
13533.038674033149N75858
14532.666666666667N624JB
15532.666666666667N569JB
16532.666666666667N3749D
17531.23595505618N523JB
18529.723756906077N504JB
19529.723756906077N637JB
20529.723756906077N506JB
21529.120879120879N571UA
22527.213114754098N37267
23526.813186813187N608JB
24526.813186813187N3771K
25526.813186813187N595JB
26526.378378378378N5ETAA
27526.113074204947N76065
28525.414364640884N26208
29525.414364640884N37419
30524.508196721311N439UA
31
32148.148148148148N37252
33147.741935483871N828AS
34147.692307692308N950UW
35147.692307692308N713UW
36147.692307692308N950UW
37144N756US
38144N950UW
39144N958UW
40140.487804878049N946UW
41140.487804878049N956UW
42140.487804878049N947UW
43140.487804878049N945UW
44140.25N3FEAA
45137.142857142857N952UW
46137.142857142857N950UW
47137.142857142857N957UW
48133.953488372093N963UW
49133.953488372093N954UW
50131.752577319588N813MQ
51130.46511627907N3DRAA
52128N760US
53124.285714285714N13913
54122.608695652174N8943A
55122.553191489362N947UW
56120N956UW
57117.551020408163N957UW
58115.2N957UW
59112.8N8623A
60110.769230769231N959UW
6176.8N755US

In [50]:
nycflights %>%
  group_by(tailnum) %>%
  summarise(mean_as = mean(avg_speed)) %>%
  arrange(desc(mean_as))


Out[50]:
tailnummean_as
1N526AS509.257950530035
2N637DL505.994764397906
3N66051504.71186440678
4N907JB504.631578947368
5N522VA502.941176470588
6N5BTAA499.375
7N654UA498.582089552239
8N382HA494.831019007655
9N75861494.769230769231
10N5DRAA493.115976519118
11N374AA491.278195488722
12N389HA490.337866153747
13N537AS490.204081632653
14N69063489.724569000401
15N68061488.965517241379
16N76065487.693908344559
17N77871487.181249870808
18N526VA485.306939916162
19N399AA484.875
20N380HA484.688134465044
21N391HA484.524084464903
22N388HA482.20229466452
23N385HA481.87447919347
24N376AA479.345512796064
25N5EJAA478.496500234831
26N386HA478.21573120198
27N56859477.387862837861
28N7BGAA476.934306569343
29N177DZ475.966386554622
30N199DN475.373357781046
31
32N965UW278.755486161109
33N506MJ275.792854275391
34N8837B274.979288557528
35N755US274.921681499977
36N521LR274.8
37N8968E274.32319501285
38N959UW272.739146108763
39N8847A272.695782078208
40N835MQ272.6262505002
41N8390A272.247163435217
42N949UW270.887567769774
43N8943A270.780746020137
44N8891A270.254496855872
45N756US269.620501378321
46N501MJ269.499430706903
47N923MQ268.64940869528
48N668MQ268.423998466552
49N963UW267.834729305356
50N858MQ267.286821705426
51N958UW266.683971229054
52N8409N262.857142857143
53N635MQ258.227848101266
54N950UW251.928468657486
55N8905F250.343107883682
56N504MJ249.818181818182
57N823AY248.893984962406
58N513MJ244.266666666667
59N956UW241.554835818005
60N8588D240
61N819MQ236.666666666667

9. Make a scatterplot of avg_speed vs. distance. Which of the following is true about the relationship between average speed and distance.

  1. As distance increases the average speed of flights decreases.
  2. The relationship is linear.
  3. There is an overall postive association between distance and average speed.
  4. There are no outliers.
  5. The distribution of distances are uniform over 0 to 5000 miles.

In [53]:
ggplot(data = nycflights, aes(x = distance, y = avg_speed)) +
  geom_point()


10. Suppose you define a flight to be "on time" if it gets to the destination on time or earlier than expected, regardless of any departure delays. Mutate the data frame to create a new variable called arr_type with levels "on time" and "delayed" based on this definition. Then, determine the on time arrival percentage based on whether the flight departed on time or not. What percent of flights that were "delayed" departing arrive "on time"?


In [83]:
nycflights <- nycflights %>%
  mutate(arr_type = ifelse(arr_delay <= 0, "arr on time", "delayed"))

In [84]:
table(nycflights$arr_type, nycflights$dep_type)


Out[84]:
             
              delayed on time
  arr on time    1898   17375
  delayed        8453    5009

In [85]:
1898 / (19273+13462) # This is the correct answer


Out[85]:
0.057980754544066

In [90]:
nycflights %>%
  summarise(ot_dep_rate = sum(arr_type == "arr on time" & dep_type == "delayed") / n())


Out[90]:
ot_dep_rate
10.05798075

In [ ]:


In [73]:
ggplot(data = nycflights, aes(x = arr_delay)) +
  geom_histogram(binwidth = 15)