library(readr)
library(ggplot2)
library(lubridate)
## 
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
# Assuming the dataset is in a CSV file named "scripps_co2_data.csv"
scripps_data <- read_delim("/Users/joonpiter/Downloads/INFO201 HW/data/scripps-co2.csv")
## Rows: 792 Columns: 11
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: "\t"
## chr  (1): station
## dbl (10): year, month, date (excel), date (year), co2, co2 (seasonally adjus...
## 
## ℹ 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.
# Checking the structure of the dataset
str(scripps_data)
## spc_tbl_ [792 × 11] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ year                     : num [1:792] 1958 1958 1958 1958 1958 ...
##  $ month                    : num [1:792] 1 2 3 4 5 6 7 8 9 10 ...
##  $ date (excel)             : num [1:792] 21200 21231 21259 21290 21320 ...
##  $ date (year)              : num [1:792] 1958 1958 1958 1958 1958 ...
##  $ co2                      : num [1:792] -100 -100 316 317 318 ...
##  $ co2 (seasonally adjusted): num [1:792] -100 -100 314 315 315 ...
##  $ co2 (seasonal, smoothed) : num [1:792] -100 -100 316 317 318 ...
##  $ co2 (smoothed)           : num [1:792] -100 -100 315 315 315 ...
##  $ co2 (filled)             : num [1:792] -100 -100 316 317 318 ...
##  $ co2 (adjusted, filled)   : num [1:792] -100 -100 314 315 315 ...
##  $ station                  : chr [1:792] "MLO" "MLO" "MLO" "MLO" ...
##  - attr(*, "spec")=
##   .. cols(
##   ..   year = col_double(),
##   ..   month = col_double(),
##   ..   `date (excel)` = col_double(),
##   ..   `date (year)` = col_double(),
##   ..   co2 = col_double(),
##   ..   `co2 (seasonally adjusted)` = col_double(),
##   ..   `co2 (seasonal, smoothed)` = col_double(),
##   ..   `co2 (smoothed)` = col_double(),
##   ..   `co2 (filled)` = col_double(),
##   ..   `co2 (adjusted, filled)` = col_double(),
##   ..   station = col_character()
##   .. )
##  - attr(*, "problems")=<externalptr>
# 2. Keep only variables year, month, and co2
scripps_data <- scripps_data[, c("year", "month", "co2")]

# 3. What does a line in this dataset represent?

#Each line in this dataset represents a monthly record of carbon dioxide (CO2) concentrations, measured in parts per million (ppm), at a specific monitoring station. 
#The columns provide information such as the year, month, day, decimal date, and the measured CO2 concentrations. 
#Additionally, the last column indicates the monitoring station, with "MLO" likely referring to the Mauna Loa Observatory. 
#The dataset spans several years, with each row corresponding to a specific month's CO2 measurements.


# 4. How are missing values coded in this dataset?
#In this dataset, missing values are coded as "-99.99."
#This is evident in columns where the data is not available or recorded, and the placeholder "-99.99" is used to indicate the absence of a valid measurement or information for that particular entry.
#For example, in the last three entries of the "2023" year, the CO2 concentrations are listed as "-99.99" for the months October, November, and December. 
#This convention is commonly used in environmental datasets to denote missing or unavailable data.

# 5. Which time period does the dataset represent?
# Print the range of years in the dataset
cat("Time period of the dataset:", min(scripps_data$year), "to", max(scripps_data$year), "\n")
## Time period of the dataset: 1958 to 2023
# 6. Make a plot showing how the CO2 concentration in the atmosphere has changed over years.

Scripps2 <- scripps_data[scripps_data$co2 != -99.99, ]

ggplot(Scripps2, aes(x = year, y = co2)) +
  geom_point(size = 1.3) +
  geom_line() +
  labs(title = "CO2 Concentration Over Years",
       x = "Year",
       y = "CO2 Concentration (ppm)")

# Save the plot as an image (optional)
ggsave("co2_concentration_plot.png", height = 6, width = 10)

# 7. Comment the graph. How has CO2 level changed over the last 60 years?
# Over the past 60 year the co2 concentrations have risen sigfigenty
# Load necessary libraries
library(readr)
library(ggplot2)

# HadCRUT data
hadcrut_data <- read_delim("/Users/joonpiter/Downloads/INFO201 HW/data/hadcrut-5.0.1.0-annual.csv")
## Rows: 174 Columns: 4
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: "\t"
## dbl (4): Time, Anomaly (deg C), Lower confidence limit (2.5%), Upper confide...
## 
## ℹ 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.
# What does a line in this dataset represent?
#The line in the dataset repersent the rise of global surface temperature anomoanly over timee

# Which time period does the dataset represent?

# The dataset repersents form 1850-2020

# Displaying the first few rows to ensure it looks good
head(hadcrut_data)
## # A tibble: 6 × 4
##    Time `Anomaly (deg C)` `Lower confidence limit (2.5%)` Upper confidence lim…¹
##   <dbl>             <dbl>                           <dbl>                  <dbl>
## 1  1850            -0.418                          -0.589                -0.246 
## 2  1851            -0.233                          -0.412                -0.0548
## 3  1852            -0.229                          -0.409                -0.0494
## 4  1853            -0.270                          -0.430                -0.111 
## 5  1854            -0.292                          -0.433                -0.150 
## 6  1855            -0.297                          -0.439                -0.155 
## # ℹ abbreviated name: ¹​`Upper confidence limit (97.5%)`
# Filter data for years 1900 and before
pre_industrial_data <- hadcrut_data[hadcrut_data$Time <= 1900, ]

# pre-industrial average temperature anomaly
pre_industrial_avg <- mean(pre_industrial_data$`Anomaly (deg C)`)

#new column for temperature anomaly over the pre-industrial average
hadcrut_data$Anomaly_over_Pre_Industrial <- hadcrut_data$`Anomaly (deg C)` - pre_industrial_avg

# Display the new column
head(hadcrut_data)
## # A tibble: 6 × 5
##    Time `Anomaly (deg C)` `Lower confidence limit (2.5%)` Upper confidence lim…¹
##   <dbl>             <dbl>                           <dbl>                  <dbl>
## 1  1850            -0.418                          -0.589                -0.246 
## 2  1851            -0.233                          -0.412                -0.0548
## 3  1852            -0.229                          -0.409                -0.0494
## 4  1853            -0.270                          -0.430                -0.111 
## 5  1854            -0.292                          -0.433                -0.150 
## 6  1855            -0.297                          -0.439                -0.155 
## # ℹ abbreviated name: ¹​`Upper confidence limit (97.5%)`
## # ℹ 1 more variable: Anomaly_over_Pre_Industrial <dbl>
# line plot
ggplot(hadcrut_data, aes(x = Time, y = Anomaly_over_Pre_Industrial)) +
  geom_line() +
  labs(title = "Global Surface Temperature Anomaly Over Time",
       x = "Year",
       y = "Temperature Anomaly (°C)")

# What kind of variables you can imagine to use to merge CO2 data with global temperature
#data–what might be the merge key?

#If "Time" in HadCrut were changed to "Year" that would be the merge key

#But we have a problem. CO2 data is monthly but temperature data yearly only. How might
#you still be able to merge these two datasets?

#To merge datasets with different time frame (monthly vs. yearly), you can create a new column in the CO2 dataset that represents the year.
#You can then use this new column to perform the merge with the yearly temperature data. 
#This is done by matching the years in both datasets.

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
co2_yearly <- scripps_data[scripps_data$co2 != -99.99, ] %>%
  group_by(year) %>%
  summarize(mean_co2 = mean(co2, na.rm = TRUE))

# join temperature and CO2 data
merged_data <- inner_join(hadcrut_data, co2_yearly, by = c("Time" = "year"))

# Create a decade column for coloring
merged_data$decade <- cut(merged_data$Time, breaks = seq(1950, 2020, by = 10), labels = seq(1950, 2010, by = 10))

# Make a plot with switched x and y-axis
ggplot(merged_data, aes(x = mean_co2, y = `Anomaly (deg C)`, color = decade)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE, color = "blue") +
  geom_hline(yintercept = 1.5, linetype = "dashed", color = "red") +
  labs(title = "Global Temperature vs CO2 Levels",
       x = "Mean CO2 Concentration (ppm)",
       y = "Temperature Anomaly (°C)",
       color = "Decade") +
  theme_minimal()
## `geom_smooth()` using formula = 'y ~ x'

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ forcats 1.0.0     ✔ tibble  3.2.1
## ✔ purrr   1.0.2     ✔ tidyr   1.3.0
## ✔ stringr 1.5.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
# Step 1: Load and inspect the UAH data
uah_data <-  read_delim("/Users/joonpiter/Downloads/INFO201 HW/data/UAH-lower-troposphere-wide.csv")
## Rows: 538 Columns: 29
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: "\t"
## dbl (29): year, month, globe, globe_land, globe_ocean, nh, nh_land, nh_ocean...
## 
## ℹ 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.
uah_data <- uah_data[, c("year", "month", "globe")]

uah_yearly <- uah_data %>%
  group_by(year) %>%
  summarize(mean_anomaly = mean(globe, na.rm = TRUE))

# Step 3: Merge HadCRUT and UAH data
merged_data <- inner_join(hadcrut_data, uah_yearly, by = c("Time" = "year"))

# Step 4: Reshape into long form using pivot_longer
merged_data_long <- merged_data %>%
  pivot_longer(cols = c(`Anomaly (deg C)`, mean_anomaly),
               names_to = "type",
               values_to = "anomaly")

# Step 5: Plot temperature anomaly changes over years
ggplot(merged_data_long, aes(x = Time, y = anomaly, color = type)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE, aes(group = type)) +
  labs(title = "Temperature Anomaly Changes Over Years",
       x = "Year",
       y = "Temperature Anomaly",
       color = "Type") +
  theme_minimal()
## `geom_smooth()` using formula = 'y ~ x'