I, YiTao Wang, hereby state that I have not gained information in any way not allowed by the exam rules during this exam, and that all work is my own.
library(tidyverse)
library(openintro)
library(nycflights13)
library(lubridate)
library(dplyr)
library(tidyr)
library(ggplot2)
The following questions shall be answered by working with the
world_bank_pop and who data sets from the
openinto library.
world_bank_pop is not clean. Clean the
data set such that the after data tidying you have six columns:
country, year, SP.URB.TOTL,
SP.URB.GROW, SP.POP.TOTL,
SP.POP.GROW. Give your code and show the first 10 rows of
the data set after being tidied. Then explain the meaning of each
column.tidy_pop <- world_bank_pop %>%
pivot_longer(cols = `2000`:`2017`, names_to = "year", values_to = "value") %>%
pivot_wider(names_from = indicator, values_from = value)
head(tidy_pop, 10)
Answer: country: Country code (short name for
country) year: Year of the data SP.URB.TOTL: How many people live in
cities SP.URB.GROW: Growth (%) of city population SP.POP.TOTL: Total
number of people SP.POP.GROW: Growth (%) of total population
country column of the tided data set in
step a) with full names of the country (for example, replace
USA with United States of America) by checking
the data frame who, which contains the full name of each
country corresponding to the three-digit country code. Give your code
and show the updated data set in a manner to illustrate that the task is
correctly fulfilled.country_names <- who %>%
select(country, iso3) %>%
distinct()
updated_pop <- tidy_pop %>%
left_join(country_names, by = c("country" = "iso3")) %>%
select(country = country.y, year, SP.URB.TOTL, SP.URB.GROW, SP.POP.TOTL, SP.POP.GROW)
head(updated_pop)
Answer: Now the table has country names.
library(tidyverse)
names_map <- who %>% select(country, iso3) %>% distinct(iso3, .keep_all = TRUE)
urban_data <- world_bank_pop %>%
pivot_longer(`2000`:`2017`, names_to = "year", values_to = "val") %>%
pivot_wider(names_from = indicator, values_from = val) %>%
inner_join(names_map, by = c("country" = "iso3")) %>%
select(country = country.y, year, SP.URB.TOTL, SP.POP.TOTL)
urban_change <- urban_data %>%
filter(year %in% c("2000", "2017")) %>%
mutate(ratio = SP.URB.TOTL / SP.POP.TOTL) %>%
select(country, year, ratio) %>%
pivot_wider(names_from = year, values_from = ratio) %>%
mutate(diff = (`2017` - `2000`) * 100) %>%
arrange(desc(diff))
head(urban_change, 10)
Answer: Equatorial Guinea is on top, China is at
second.
For the following tasks, use data set planes and
flights from the nycflights13 package.
planes data set, only keep planes from
manufacturers that have more than 10 samples in the data set. Then
convert manufacturer column into a factor. Then combine
AIRBUS and AIRBUS INDUSTRIE as a single
category AIRBUS; combine MCDONNELL DOUGLAS,
MCDONNELL DOUGLAS AIRCRAFT CO and
MCDONNELL DOUGLAS CORPORATION into a single category
MCDONNELL. Save your data frame as a new one. Show your
code and the first 10 rows of the updated data frame.planes_filtered <- planes %>%
group_by(manufacturer) %>%
filter(n() > 10) %>%
ungroup()
planes_factor <- planes_filtered %>%
mutate(manufacturer = fct_collapse(
manufacturer,
"AIRBUS" = c("AIRBUS", "AIRBUS INDUSTRIE"),
"MCDONNELL" = c("MCDONNELL DOUGLAS",
"MCDONNELL DOUGLAS AIRCRAFT CO",
"MCDONNELL DOUGLAS CORPORATION")
))
planes_clean <- planes_factor
head(planes_clean, 10)
Answer: All Airbus aircraft variants have now been
standardized as “AIRBUS,” while all McDonnell Douglas entries have been
standardized as “MCDONNELL.”
flights data set with the planes
data set, study how plane models correlate with the flight distance with
proper data visualizations or summary tables. You are required to
summarize your findings concisely in your own words.flight_plane <- flights %>%
left_join(planes, by = "tailnum")
top_models <- flight_plane %>%
count(model) %>%
arrange(desc(n)) %>%
head(15) %>%
pull(model)
model_distance <- flight_plane %>%
filter(model %in% top_models) %>%
group_by(model) %>%
summarise(avg_distance = mean(distance, na.rm = TRUE),
n_flights = n()) %>%
arrange(desc(avg_distance))
model_distance
top10_models_dist <- head(model_distance, 10) %>% pull(model)
flight_plane %>%
filter(model %in% top10_models_dist) %>%
ggplot(aes(x = reorder(model, distance, FUN = median), y = distance)) +
geom_boxplot(outlier.alpha = 0.3) +
coord_flip() +
labs(x = "Plane Model", y = "Flight Distance (miles)",
title = "Flight Distance by Plane Model (Top 10)")
Answer: There is a strong correlation between
aircraft model and flight distance, reflecting the adaptability of
aircraft design to varying flight ranges.
For the following tasks, use the data set weather,
flights or planes from the
nycflights13 package.
JFK airport. (Hint: You need to first create a
datetime variable for each hour.)jfk_weather <- weather %>%
filter(origin == "JFK", year == 2013) %>%
mutate(datetime = make_datetime(year, month, day, hour))
ggplot(jfk_weather, aes(x = datetime, y = temp)) +
geom_line(color = "tomato", alpha = 0.7) +
geom_smooth(method = "loess", span = 0.05, se = FALSE, color = "darkred") +
labs(x = "Date", y = "Temperature (F)",
title = "Hourly Temperature at JFK Airport in 2013") +
theme_minimal()
Answer: This chart illustrates the seasonal cycle:
cold winters and warm summers.
daily_range <- jfk_weather %>%
group_by(year, month, day) %>%
summarise(temp_range = max(temp, na.rm = TRUE) - min(temp, na.rm = TRUE),
.groups = "drop") %>%
slice_max(temp_range, n = 1)
daily_range
Answer: At 2013/5/8 has the largest temperature
difference.
flights data set. Here overnight
flights are defined as flights that departed between 10pm and 1am, and
having an air time of over 4 hours . Create a categorical variable
overnight_flag with YES or NO as
the possible values. Show your code and the updated data frame.flights_overnight <- flights %>%
mutate(
overnight_flag = ifelse(
(sched_dep_time >= 2200 | sched_dep_time <= 100) &
air_time > 240,
"YES", "NO"
)
)
flights_overnight %>%
select(year:day, dep_time, sched_dep_time, air_time, overnight_flag) %>%
head(15)
Answer: The overnight_flag column marks flights that
meet the red‑eye definition. The updated data frame includes this
variable.
planes data set.overnight_planes <- flights_overnight %>%
left_join(planes, by = "tailnum")
ggplot(overnight_planes, aes(x = overnight_flag, y = seats, fill = overnight_flag)) +
geom_boxplot(alpha = 0.7) +
labs(x = "Overnight Flight", y = "Number of Seats",
title = "Aircraft Size (Seats) for Overnight vs. Non‑Overnight Flights") +
theme_minimal() +
scale_fill_manual(values = c("NO" = "gray70", "YES" = "salmon"))
## Warning: Removed 52606 rows containing non-finite outside the scale range
## (`stat_boxplot()`).
overnight_planes %>%
group_by(overnight_flag) %>%
summarise(avg_seats = mean(seats, na.rm = TRUE),
median_seats = median(seats, na.rm = TRUE),
n = n())
Answer: In direct contrast to the aforementioned
claim, night flights tend to utilize larger—rather than smaller—aircraft
models.
Answer the following questions with data visualization or summary. You are required to summarize your findings concisely in your own words and support your conclusion with proper graphs or tables.
gss_cat data set, find factors that are
significantly correlated with the reported income.Answer: <>
smoking data set of the openintro
package, find find factors that are significantly correlated with the
smoking status and the number of cigarettes smoked per day.# Enter code here.
Answer: