library(dplyr)
## 
## 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
library(ggplot2)
library(nycflights13)
library(lubridate)
## 
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
# Question 1.1: Load the dataset and check that it looks good.
head(flights) 
## # A tibble: 6 × 19
##    year month   day dep_time sched_dep_time dep_delay arr_time sched_arr_time
##   <int> <int> <int>    <int>          <int>     <dbl>    <int>          <int>
## 1  2013     1     1      517            515         2      830            819
## 2  2013     1     1      533            529         4      850            830
## 3  2013     1     1      542            540         2      923            850
## 4  2013     1     1      544            545        -1     1004           1022
## 5  2013     1     1      554            600        -6      812            837
## 6  2013     1     1      554            558        -4      740            728
## # ℹ 11 more variables: arr_delay <dbl>, carrier <chr>, flight <int>,
## #   tailnum <chr>, origin <chr>, dest <chr>, air_time <dbl>, distance <dbl>,
## #   hour <dbl>, minute <dbl>, time_hour <dttm>
# Question 1.2a: Are there any airport codes that are not three characters long?
sum(nchar(flights$dest) != 3)
## [1] 0
# Question 1.2b: Are there any airport codes that contain digits?
sum(grepl("[0-9]", flights$dest))
## [1] 0
# Question 1.3: How many missing arrival delay variables are there in data?
sum(is.na(flights$arr_delay))
## [1] 9430
# Explanation: Discuss whether missing arrival delay values are a problem for the analysis.

# Question 1.4: Are there any implausible values in the delay variable?
# Consider negative values or excessively large values.

# Question 1.5: Compute average delay by destinations. Print the worst three destinations.
worst_destinations <- flights %>%
  group_by(dest) %>%
  summarize(avg_delay = mean(arr_delay, na.rm = TRUE)) %>%
  arrange(desc(avg_delay)) %>%
  head(3)
print(worst_destinations)
## # A tibble: 3 × 2
##   dest  avg_delay
##   <chr>     <dbl>
## 1 CAE        41.8
## 2 TUL        33.7
## 3 OKC        30.6
# Question 1.6: Compute and print the average delay by month.
avg_delay_by_month <- flights %>%
  group_by(month) %>%
  summarize(avg_delay = mean(arr_delay, na.rm = TRUE))
print(avg_delay_by_month)
## # A tibble: 12 × 2
##    month avg_delay
##    <int>     <dbl>
##  1     1     6.13 
##  2     2     5.61 
##  3     3     5.81 
##  4     4    11.2  
##  5     5     3.52 
##  6     6    16.5  
##  7     7    16.7  
##  8     8     6.04 
##  9     9    -4.02 
## 10    10    -0.167
## 11    11     0.461
## 12    12    14.9
# Question 1.7: Make a barplot of the monthly delays.
ggplot(avg_delay_by_month, aes(x = factor(month), y = avg_delay, fill = factor(month))) +
  geom_bar(stat = "identity") +
  scale_fill_hue() +
  labs(title = "Monthly Average Delays", x = "Month", y = "Average Delay") +
  theme_minimal()

# Question 1.8: Make a scatterplot of daily delays in 2013.
flights_2013 <- filter(flights, year == 2013)
ggplot(flights_2013, aes(x = as.numeric(format(time_hour, "%j")), y = arr_delay)) +
  geom_point(alpha = 0.5) +
  labs(title = "Daily Delays in 2013", x = "Day of Year", y = "Arrival Delay") +
  theme_minimal()
## Warning: Removed 9430 rows containing missing values (`geom_point()`).

# Explanation: When analyzing the scatterplot it seems to have it highest peak at the start of the year, I suspect this is due to the holiday rush and weather of winter
# Question 2.1: How many flights were there to Chicago?
flights_to_ORD <- filter(flights, dest == "ORD")
num_flights_to_ORD <- nrow(flights_to_ORD)
print(num_flights_to_ORD)
## [1] 17283
# Explanation: Discuss the number of flights to Chicago.

# Question 2.2: Which was the fastest flight to Chicago (shortest airtime)?
fastest_flight_to_ORD <- flights_to_ORD %>%
  filter(air_time == min(air_time, na.rm = TRUE)) %>%
  select(month,day, dep_time, air_time, carrier, origin)
print(fastest_flight_to_ORD)
## # A tibble: 1 × 6
##   month   day dep_time air_time carrier origin
##   <int> <int>    <int>    <dbl> <chr>   <chr> 
## 1     8    21     1604       87 UA      EWR
# Explanation: Discuss the details of the fastest flight to Chicago.

# Question 2.3: Look up flight time from NYC to ORD. What are the typical flight times for direct flights?
# Check external sources for typical flight times.

# Question 2.4: Find the slowest flight to Chicago (longest airtime).
slowest_flight_to_ORD <- flights_to_ORD %>%
  filter(air_time == max(air_time, na.rm = TRUE)) %>%
  select(month,day, dep_time, air_time, carrier, origin)
print(slowest_flight_to_ORD)
## # A tibble: 1 × 6
##   month   day dep_time air_time carrier origin
##   <int> <int>    <int>    <dbl> <chr>   <chr> 
## 1     4    10      638      198 UA      EWR
# Explanation: Discuss the details of the slowest flight to Chicago.

# Question 2.5: Compute flight speed (using air time and distance) for all flights to Chicago.
flights_to_ORD <- mutate(flights_to_ORD, speed = distance / (air_time / 60))
fastest_slowest_flights <- flights_to_ORD %>%
  arrange(speed) %>%
  slice(c(1:3, n(), n()-1, n()-2)) %>%
  select(month,day, dep_time, carrier)
#Question 2.6 Make a plot of delay versus speed for all flights to Chicago. 
library(ggplot2)

# Scatter plot with color representing departure delay and size representing distance
ggplot(flights_to_ORD, aes(x = speed, y = dep_delay, color = dep_delay, size = distance)) +
  geom_point(alpha = 0.7) +
  scale_color_gradient(low = "green", high = "red", guide = "legend") +
  labs(title = "Flight Speed vs. Departure Delay to Chicago",
       x = "Flight Speed (mph)",
       y = "Departure Delay (minutes)",
       size = "Distance") +
  theme_minimal()
## Warning: Removed 717 rows containing missing values (`geom_point()`).

#**Explination: Scatter plots are effective for visualizing relationships between two continuous variables, making them suitable for comparing flight speed and departure delay.
# The scatter plot shows the distribution of data points, helping identify patterns, clusters, or trends.**
# Load required libraries
library(dplyr)
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ forcats 1.0.0     ✔ stringr 1.5.0
## ✔ purrr   1.0.2     ✔ tibble  3.2.1
## ✔ readr   2.1.4     ✔ tidyr   1.3.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
# Question 2.1.1: Load data. How many rows/columns do we have?
gapminder <- read_delim("/Users/joonpiter/Downloads/gapminder.csv.bz2")
## Rows: 13055 Columns: 25
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: "\t"
## chr  (6): iso3, name, iso2, region, sub-region, intermediate-region
## dbl (19): time, totalPopulation, fertilityRate, lifeExpectancy, childMortali...
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
dim(gapminder)  # Display the number of rows and columns
## [1] 13055    25
# Question 2.1.2: Print a small sample of data. Does it look OK?
head(gapminder)
## # A tibble: 6 × 25
##   iso3  name  iso2  region   `sub-region`            `intermediate-region`  time
##   <chr> <chr> <chr> <chr>    <chr>                   <chr>                 <dbl>
## 1 ABW   Aruba AW    Americas Latin America and the … Caribbean              1960
## 2 ABW   Aruba AW    Americas Latin America and the … Caribbean              1961
## 3 ABW   Aruba AW    Americas Latin America and the … Caribbean              1962
## 4 ABW   Aruba AW    Americas Latin America and the … Caribbean              1963
## 5 ABW   Aruba AW    Americas Latin America and the … Caribbean              1964
## 6 ABW   Aruba AW    Americas Latin America and the … Caribbean              1965
## # ℹ 18 more variables: totalPopulation <dbl>, fertilityRate <dbl>,
## #   lifeExpectancy <dbl>, childMortality <dbl>, youthFemaleLiteracy <dbl>,
## #   youthMaleLiteracy <dbl>, adultLiteracy <dbl>, GDP_PC <dbl>,
## #   accessElectricity <dbl>, agriculturalLand <dbl>, agricultureTractors <dbl>,
## #   cerealProduction <dbl>, fertilizerHa <dbl>, co2 <dbl>,
## #   greenhouseGases <dbl>, co2_PC <dbl>, pm2.5_35 <dbl>, battleDeaths <dbl>
# Question 2.1.3: How many countries are there in the dataset? Analyze iso3, iso2, and name.
num_countries_iso3 <- gapminder %>% distinct(iso3) %>% nrow()
num_countries_iso2 <- gapminder %>% distinct(iso2) %>% nrow()
num_countries_name <- gapminder %>% distinct(name) %>% nrow()

print(num_countries_iso3)
## [1] 253
print(num_countries_iso2)
## [1] 249
print(num_countries_name)
## [1] 250
# Explanation: Discuss the differences in counts for iso3, iso2, and name.
# Load necessary libraries
library(dplyr)

# 2.1 Descriptive statistics
# 1. Load data. How many rows/columns do we have?
 gapminder <- read_delim("/Users/joonpiter/Downloads/gapminder.csv.bz2")
## Rows: 13055 Columns: 25
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: "\t"
## chr  (6): iso3, name, iso2, region, sub-region, intermediate-region
## dbl (19): time, totalPopulation, fertilityRate, lifeExpectancy, childMortali...
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# Display the number of rows and columns
cat("Number of rows:", nrow(gapminder), "\n")
## Number of rows: 13055
cat("Number of columns:", ncol(gapminder), "\n")
## Number of columns: 25
# 2. Print a small sample of data. Does it look OK?
head(gapminder)
## # A tibble: 6 × 25
##   iso3  name  iso2  region   `sub-region`            `intermediate-region`  time
##   <chr> <chr> <chr> <chr>    <chr>                   <chr>                 <dbl>
## 1 ABW   Aruba AW    Americas Latin America and the … Caribbean              1960
## 2 ABW   Aruba AW    Americas Latin America and the … Caribbean              1961
## 3 ABW   Aruba AW    Americas Latin America and the … Caribbean              1962
## 4 ABW   Aruba AW    Americas Latin America and the … Caribbean              1963
## 5 ABW   Aruba AW    Americas Latin America and the … Caribbean              1964
## 6 ABW   Aruba AW    Americas Latin America and the … Caribbean              1965
## # ℹ 18 more variables: totalPopulation <dbl>, fertilityRate <dbl>,
## #   lifeExpectancy <dbl>, childMortality <dbl>, youthFemaleLiteracy <dbl>,
## #   youthMaleLiteracy <dbl>, adultLiteracy <dbl>, GDP_PC <dbl>,
## #   accessElectricity <dbl>, agriculturalLand <dbl>, agricultureTractors <dbl>,
## #   cerealProduction <dbl>, fertilizerHa <dbl>, co2 <dbl>,
## #   greenhouseGases <dbl>, co2_PC <dbl>, pm2.5_35 <dbl>, battleDeaths <dbl>
# 3. How many countries are there in the dataset? Analyze all three: iso3, iso2, and name.
unique_countries_iso3 <- n_distinct(gapminder$iso3)
unique_countries_iso2 <- n_distinct(gapminder$iso2)
unique_countries_name <- n_distinct(gapminder$name)

cat("Number of unique countries (iso3):", unique_countries_iso3, "\n")
## Number of unique countries (iso3): 253
cat("Number of unique countries (iso2):", unique_countries_iso2, "\n")
## Number of unique countries (iso2): 249
cat("Number of unique countries (name):", unique_countries_name, "\n")
## Number of unique countries (name): 250
# 4. Find out why there are more names than iso-2 codes and more iso3-codes than iso2-codes.
# (a) Find how many names are there for each iso-2 code.
names_per_iso2 <- gapminder %>%
  group_by(iso2) %>%
  summarize(count_names = n_distinct(name))

# Check for iso-2 codes with more than one name
iso2_with_multiple_names <- filter(names_per_iso2, count_names > 1)
print(iso2_with_multiple_names)
## # A tibble: 1 × 2
##   iso2  count_names
##   <chr>       <int>
## 1 <NA>            2
# (b) Repeat the same for name and iso3-code.
names_per_iso3 <- gapminder %>%
  group_by(iso3) %>%
  summarize(count_names = n_distinct(name))

# Check for names with more than one iso3-code
names_with_multiple_iso3 <- filter(names_per_iso3, count_names > 1)
print(names_with_multiple_iso3)
## # A tibble: 0 × 2
## # ℹ 2 variables: iso3 <chr>, count_names <int>
# Load required libraries
library(dplyr)
library(ggplot2)

# Question 1: Plot how total CO2 emissions has changed over time for selected countries.
selected_countries <- c("United States", "China", "India", "Brazil", "Russia")

co2_over_time <- gapminder %>%
  filter(name %in% selected_countries) %>%
  ggplot(aes(x = time, y = co2)) +
  geom_line(aes(color = name)) +
  labs(title = "Total CO2 Emissions Over Time",
       x = "Year", y = "Total CO2 Emissions (kt)") +
  theme_minimal() +
  scale_color_brewer(palette = "Set1")

print(co2_over_time)
## Warning: Removed 9 rows containing missing values (`geom_line()`).

# **Explanation: When looking over the CO2 emissions there seems to ma massive increase once the 2000's**

# Question 2: Make a similar plot using CO2 per capita for the same countries.
co2_per_capita <- gapminder %>%
  filter(name %in% selected_countries) %>%
  ggplot(aes(x = time, y = co2_PC)) +
  geom_line(aes(color = name)) +
  labs(title = "CO2 Emissions Per Capita Over Time",
       x = "Year", y = "CO2 Emissions Per Capita (metric tons)") +
  theme_minimal() +
  scale_color_brewer(palette = "Set1")

print(co2_per_capita)
## Warning: Removed 9 rows containing missing values (`geom_line()`).

# **Explanation: The trend is still largely the same in the fact that united states had th most, but what is more intresting is that the other country were almost**
# **on the same scale but when the 1980 hit the big split seem to come off**

# Question 3: Compute average CO2 emissions per capita across continents.
average_co2_per_continent <- gapminder %>%
  group_by(region) %>%
  summarise(avg_co2_per_capita = mean(co2_PC, na.rm = TRUE))

print(average_co2_per_continent)
## # A tibble: 6 × 2
##   region   avg_co2_per_capita
##   <chr>                 <dbl>
## 1 Africa                0.930
## 2 Americas              6.46 
## 3 Asia                  6.21 
## 4 Europe                7.95 
## 5 Oceania               4.39 
## 6 <NA>                 16.2
# Explanation: North America has the highest CO2 per capitap with a avg of 16.2 with the 2nd higest being eroupe with 7.95, what is most notable is that this is not even hald of what NA producese

# Question 4: Make a barplot showing the average CO2 emissions per capita across continents in 1960 and 2016.
co2_1960_2016 <- gapminder %>%
  filter(time %in% c(1960, 2016)) %>%
  group_by(region, time) %>%
  summarise(avg_co2_per_capita = mean(co2_PC, na.rm = TRUE))
## `summarise()` has grouped output by 'region'. You can override using the
## `.groups` argument.
# Remove rows with missing values
co2_1960_2016 <- co2_1960_2016[complete.cases(co2_1960_2016), ]

barplot_data <- spread(co2_1960_2016, key = "time", value = "avg_co2_per_capita")

barplot <- ggplot(barplot_data, aes(x = region, y = `1960`)) +
  geom_bar(stat = "identity", position = position_dodge(width = 0.7), fill = "lightblue") +
  geom_bar(stat = "identity", aes(y = `2016`), position = position_dodge(width = 0.7), fill = "darkblue") +
  labs(title = "Average CO2 Emissions Per Capita Across Continents (1960 and 2016)",
       x = "Continent", y = "Average CO2 Emissions Per Capita") +
  theme_minimal()

print(barplot)

# Load required libraries
library(dplyr)
library(ggplot2)

# Question 1: Scatterplot of total fertility versus life expectancy by country for 1960.
scatterplot_1960 <- gapminder %>%
  filter(time == 1960) %>%
  ggplot(aes(x = fertilityRate, y = lifeExpectancy, color = region, size = totalPopulation)) +
  geom_point(alpha = 0.7) +
  scale_size_continuous(range = c(2, 20)) +
  labs(title = "Total Fertility vs. Life Expectancy (1960)",
       x = "Total Fertility Rate",
       y = "Life Expectancy at Birth",
       size = "Total Population",
       color = "Continent") +
  theme_minimal()

print(scatterplot_1960)
## Warning: Removed 27 rows containing missing values (`geom_point()`).

# Explanation: Discuss the patterns observed in the scatterplot for 1960.

# Question 2: Scatterplot of total fertility versus life expectancy by country for 2019.
scatterplot_2019 <- gapminder %>%
  filter(time == 2019) %>%
  ggplot(aes(x = fertilityRate, y = lifeExpectancy, color = region, size = totalPopulation)) +
  geom_point(alpha = 0.7) +
  scale_size_continuous(range = c(2, 20)) +
  labs(title = "Total Fertility vs. Life Expectancy (2019)",
       x = "Total Fertility Rate",
       y = "Life Expectancy at Birth",
       size = "Total Population",
       color = "Continent") +
  theme_minimal()

print(scatterplot_2019)
## Warning: Removed 20 rows containing missing values (`geom_point()`).

# Explanation: Discuss the patterns observed in the scatterplot for 2019.

# Question 3: Compare the two scatterplots and comment on the world's development over the last 60 years.

# Question 4: Compute average life expectancy for each continent in 1960 and 2019.
avg_life_expectancy <- gapminder %>%
  group_by(region, time) %>%
  summarise(avg_life_expectancy = mean(lifeExpectancy, na.rm = TRUE))
## `summarise()` has grouped output by 'region'. You can override using the
## `.groups` argument.
print(avg_life_expectancy)
## # A tibble: 366 × 3
## # Groups:   region [6]
##    region  time avg_life_expectancy
##    <chr>  <dbl>               <dbl>
##  1 Africa  1960                41.5
##  2 Africa  1961                41.9
##  3 Africa  1962                42.4
##  4 Africa  1963                42.8
##  5 Africa  1964                43.3
##  6 Africa  1965                43.7
##  7 Africa  1966                44.1
##  8 Africa  1967                44.6
##  9 Africa  1968                45.0
## 10 Africa  1969                45.5
## # ℹ 356 more rows
# Explanation: Discuss the average life expectancy for each continent in 1960 and 2019.

# Question 5: Compute average life expectancy growth from 1960-2019 across continents.
avg_growth <- avg_life_expectancy %>%
  group_by(region) %>%
  mutate(lag_life_expectancy = lag(avg_life_expectancy),
         growth = avg_life_expectancy - lag_life_expectancy) %>%
  summarise(avg_growth = mean(growth, na.rm = TRUE))

print(avg_growth)
## # A tibble: 6 × 2
##   region   avg_growth
##   <chr>         <dbl>
## 1 Africa        0.384
## 2 Americas      0.291
## 3 Asia          0.389
## 4 Europe        0.188
## 5 Oceania       0.290
## 6 <NA>          0.120
# Explanation: Asia seems to have the highest life expentency, with the Africa not far behind then being followd up by the Americas, Oceania and Europe

# Question 6: Show the movement of selected countries on the total fertility–life expectancy space.
selected_countries <- c("United States", "Sweden", "China", "Gabon", "Mongolia", "Turkey")

countries_movement <- gapminder %>%
  filter(name %in% selected_countries) %>%
  ggplot(aes(x = fertilityRate, y = lifeExpectancy, color = name)) +
  geom_point() +
  labs(title = "Movement of Countries in Total Fertility–Life Expectancy Space",
       x = "Total Fertility Rate",
       y = "Life Expectancy at Birth",
       color = "Country") +
  theme_minimal() +
  geom_text(aes(label = name), hjust = 1, vjust = 1)

print(countries_movement)

# Explanation: Discuss the movement of selected countries in the scatterplot.

# Question 7: Ranking of the United States in terms of life expectancy in 1960 and 2019.
us_rank_1960 <- gapminder %>%
  filter(name == "United States of America" & time == 1960) %>%
  arrange(desc(lifeExpectancy)) %>%
  mutate(rank = row_number()) %>%
  select(rank, lifeExpectancy)

us_rank_2019 <- gapminder %>%
  filter(name == "United States of America" & time == 2019) %>%
  arrange(desc(lifeExpectancy)) %>%
  mutate(rank = row_number()) %>%
  select(rank, lifeExpectancy)

print(us_rank_2019)
## # A tibble: 1 × 2
##    rank lifeExpectancy
##   <int>          <dbl>
## 1     1           78.8
print(us_rank_1960)
## # A tibble: 1 × 2
##    rank lifeExpectancy
##   <int>          <dbl>
## 1     1           69.8
# the following code is computing however it is spitting back out the rank for USA as 1 when I know that not the case, im not sure why the ouput is that
#I spent approximately 9 hours on this problem set over 2 days