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 32735 domestic flights that departed from the three major New York City airports in 2013. You 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.
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. This particular
version of the flights data is contained in the openintro
package and the dataset is called nycflights
.
To view the names of the variables, type the command
names(nycflights)
This returns the names of the variables in this data frame. The codebook (description of the variables) is included below.
year
, month
, day
: Date of
departuredep_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 AirwaysDL
: Delta Air Lines Inc.EV
: ExpressJet Airlines Inc.F9
: Frontier Airlines Inc.FL
: AirTran Airways CorporationHA
: Hawaiian Airlines Inc.MQ
: Envoy AirOO
: SkyWest Airlines Inc.UA
: United Air Lines Inc.US
: US Airways Inc.VX
: Virgin AmericaWN
: Southwest Airlines Co.YV
: Mesa Airlines Inc.tailnum
: Plane tail numberflight
: Flight numberorigin
, 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.
str(nycflights)
The nycflights
data frame is a massive trove of
information. Let’s think about some questions we might want to answer
with these data:
The dplyr
package (which is part of the
tidyverse
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.
We can examine the distribution of departure delays of all flights with a histogram.
ggplot(data = nycflights) +
geom_histogram(aes(x = dep_delay)) +
labs(x = "Departure Delays, in minutes", y = "Count")
Histograms are generally a very good way to see the shape of a single distribution of numerical data, 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:
ggplot(data = nycflights) +
geom_histogram(aes(x = dep_delay), binwidth = 15) +
labs(x = "Departure Delays, in minutes", y = "Count")
ggplot(data = nycflights) +
geom_histogram(aes(x = dep_delay), binwidth = 150) +
labs(x = "Departure Delays, in minutes", y = "Count")
If we want to focus on departure delays of flights headed to ORD
only, we need to first filter
the data for flights headed
to ORD (dest == "ORD"
) and then make a histogram of only
departure delays of only those flights.
<- nycflights %>% filter(dest == "ORD")
ord_flights ggplot(data = ord_flights) +
geom_histogram(aes(x = dep_delay)) +
labs(x = "Departure Delays, in minutes (ORD only)", y = "Count")
Let’s decipher these two lines of code:
nycflights
data frame,
filter
for flights headed to ORD, and save the result as a
new data frame called ord_flights
.
==
means “if it’s equal to”.ORD
is in quotation marks since it is a character
string.geom_histogram
call from
earlier for making a histogram, except that it uses the data frame for
flights headed to ORD 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:
favstats(~ dep_delay, data = ord_flights)
The favstats()
function in the mosaic
package makes several summary statistic functions for the variable
specified, in this case dep_delay
. We can see the median,
the mean, the standard deviation (sd), and the sample size (n).
You could also calculate these summary statistics by knowing the individual function calls.
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
We can also filter based on multiple criteria. Suppose we are interested in flights headed to San Francisco (SFO) in February:
<- nycflights %>% filter(dest == "SFO", month == 2) sfo_feb_flights
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.
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?
Describe the distribution of the arrival delays of these (SFO in February) flights using a histogram and report an appropriate measure of centrality.
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 groups
paremeter
to get the same summary stats for each origin airport:
favstats(~ dep_delay, groups = origin, data = sfo_feb_flights)
Here, we first grouped the data by origin
, and then
calculated the summary statistics.
arr_delay
)
of flights in in the sfo_feb_flights
data frame, grouped by
carrier. Which carrier is the has the highest median arrival
delays?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:
arrange
these average
delays in desc
ending order. The favstats
function doesn’t have a sort option, but we can pipe it into the
arrange
function.favstats(~ dep_delay, groups = month, data = nycflights) %>%
arrange(desc(mean))
We can also visualize the distributions of departure delays across months using side-by-side boxplots:
ggplot(data = nycflights) +
geom_boxplot(aes(x = factor(month), y = dep_delay)) +
labs(x = "Month", y = "Departure Delays, in minutes")
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)
. Also, note that the extreme
outliers cause this plot to be difficult to view. Filtering out
outliers, with transparency, can be a better way to view the bulk of a
dataset with a few very extreme points.
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 or more to be “delayed”. This is the most technical part of the lab; read SLOWLY, making sure you understand each sentence and line of code.
In order to determine which airport has the best on-time departure rate, we need to
Let’s start with classifying each flight as “on-time” or “delayed” by
creating a new variable with the mutate
function.
<- 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:
%>%
nycflights group_by(origin) %>%
summarise(ot_dep_rate = sum(dep_type == "on-time") / n()) %>%
arrange(desc(ot_dep_rate))
We can also visualize the distribution of on-time departure rates across the three airports using a segmented bar plot (Section 1.7).
ggplot(data = nycflights) +
geom_bar(aes(x = origin, fill = dep_type)) +
labs(x = "Origin airport", y = "Count")
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). Hint: Average speed can be
calculated as distance divided by number of hours of travel, and note
that air_time
is given in minutes.
What is the tail number of the plane with the fastest
avg_speed
? Hint: You can sort by variables
in the Data Viewer using the arrows next to the variable names.
You can Google this tail number to find out more about the
aircraft.
Make a scatterplot of avg_speed
vs. distance
. Describe the relationship between average
speed and distance. Hint: Use
geom_point
.
Replicate the following plot. Hint: The data
frame plotted only contains flights from American Airlines, Delta
Airlines, and United Airlines, and the points are colored by
carrier
. Once you replicate the plot, determine (roughly)
what the cutoff point is for departure delays where you can still expect
to get to your destination on-time.
When you are finished with the lab, you need to upload only your
.Rmd
and .pdf
file to Schoology. Note the due
date and time. Make sure your final Markdown document Knits
properly and shows all your work. If your document doesn’t Knit, you
will receive points off. Also remember that if you needed output
(graphs, numeric output, etc.) to answer a question, the code to
generate that output needs to be in the lab report.