#student name:Yizhao Su
#student number:2204275
# Install and load required packages
install.packages("tidyverse")
install.packages("car")
install.packages("lsmeans")

# Load the necessary libraries for data manipulation and visualization
library(tidyverse)  # For data manipulation and ggplot2
library(readxl)     # For reading Excel files
library(ggplot2)    # For creating complex plots from data in a dataframe
library(dplyr)      # For data manipulation
library(tidyr)      # For data tidying
library(car)        # For Companion to Applied Regression
library(lsmeans)    # For least-squares means

## Question 1

# Read the Excel file containing Wales Climate Data, specifically the "Max Temp" sheet
WalesMaxTemp <- read_excel("C:/Users/ASUS/Desktop/Wales Climate Data.csv", sheet = "Max Temp")

# Filter the data to include only the Seasonal Max Temperature values from 1892 to 2022
# Selecting specific columns: year, winter, spring, summer, autumn temperatures
SeasonalMaxTemp <- WalesMaxTemp[WalesMaxTemp$year >= 1892 & WalesMaxTemp$year <= 2022, c("year", "win", "spr", "sum", "aut")]

# Select data for every decade starting from 1892
# This helps in analyzing long-term trends over a century
decade_data <- SeasonalMaxTemp[SeasonalMaxTemp$year %% 10 == 2 | SeasonalMaxTemp$year == 1892, ]

# Convert the 'win' (winter) column to numeric to avoid the 'Discrete value supplied to continuous scale' error
# This is necessary for ggplot2 to interpret the data correctly
decade_data$win <- as.numeric(decade_data$win)

# Plot the graph showing Wales average seasonal maximum temperatures
# Using ggplot2 for data visualization
# Each season is represented with a different color for clarity
ggplot(decade_data, aes(x = year, group = 1)) +
  geom_line(aes(y = win, color = "Winter")) +
  geom_line(aes(y = spr, color = "Spring")) +
  geom_line(aes(y = sum, color = "Summer")) +
  geom_line(aes(y = aut, color = "Autumn")) +
  geom_point(aes(y = win), color = "blue") +
  geom_point(aes(y = spr), color = "green") +
  geom_point(aes(y = sum), color = "red") +
  geom_point(aes(y = aut), color = "orange") +
  labs(title = "Wales average seasonal maximum temperatures",
       x = "Year", y = "Temperature", color = "Season") +
  scale_color_manual(values = c("Winter" = "blue", "Spring" = "green", "Summer" = "red", "Autumn" = "orange")) +
  scale_x_continuous(limits = c(1892, 2022), breaks = seq(1892, 2022, by = 10)) +
  scale_y_continuous(limits = c(4, 21), breaks = seq(0, 21, by = 1))


## Question 2

# Read the Excel file for Annual Rainfall Data
WalesRainfall <- read_excel("C:/Users/ASUS/Desktop/Wales Climate Data.csv", sheet = "Rainfall")

# Extract Annual Rainfall data from the dataset
WalesAnnRainfall <- WalesRainfall[c("year", "ann")]

# Extract Annual Maximum Temperature data from previously loaded dataset
WalesAnnMaxTemp <- WalesMaxTemp[c("year", "ann")]

# Combine Annual Rainfall and Maximum Temperature data into a new dataframe
# The 'merge' function is used to join these datasets by the 'year' column
AnnRainTemp <- merge(WalesAnnRainfall, WalesAnnMaxTemp, by = "year")

# Extract and separate the annual rainfall and maximum temperature into two vectors
rainfall <- AnnRainTemp$ann.x  # Annual rainfall data
max_temp <- AnnRainTemp$ann.y  # Annual maximum temperature data

# Calculate the Pearson correlation between annual rainfall and annual maximum temperature
correlation <- cor(rainfall, max_temp)

# Print the result with a descriptive message
print(paste("Correlation between the total annual rainfall and the annual maximum 
temperature:", correlation))

## Question 3

# Load the Excel file for Minimum Temperature Data
WalesMinTemp <- read_excel("C:/Users/ASUS/Desktop/Wales Climate Data.csv", sheet = "Min Temp")

# Filter the data to include minimum temperatures for August between 1890 and 1910
MinTemp_1890_1910 <- WalesMinTemp[WalesMinTemp$year >= 1890 & WalesMinTemp$year <= 1910, c("year", "aug")]

# Filter the data to include minimum temperatures for August between 2000 and 2020
MinTemp_2000_2020 <- WalesMinTemp[WalesMinTemp$year >= 2000 & WalesMinTemp$year <= 2020, c("year", "aug")]

# Perform a t-test to compare the mean minimum temperatures in August between the two periods
# The t.test function is used to test the hypothesis that the means of two groups are different
t_test_result <- t.test(MinTemp_1890_1910$aug, MinTemp_2000_2020$aug)

# Print the results of the t-test
# This output will include the t-statistic, degrees of freedom, p-value, and confidence interval
print(t_test_result)

## Question 4

# Read the Excel file for Annual Rain Days data
WalesRainDays <- read_excel("C:/Users/ASUS/Desktop/Wales Climate Data.csv", sheet = "Rain Days")

# Select only the 'year' and 'ann' (annual rain days) columns for analysis
WalesAnnRainDays <- WalesRainDays[c("year", "ann")]

# Filter and select data from 1980 to 2020
selected_data <- WalesAnnRainDays[WalesAnnRainDays$year >= 1980 & WalesAnnRainDays$year <= 2020, ]

# Group the selected data by decade
# The 'cut' function is used to create decade intervals
selected_data <- mutate(selected_data, decade = cut(year, breaks = seq(1980, 2020, by = 10)))

# Perform ANOVA (Analysis of Variance) to test if there are significant differences in annual rain days across decades
anova_result <- aov(ann ~ decade, data = selected_data)

# Print the summary of the ANOVA test
# The summary includes the F-statistic and the p-value, which indicates statistical significance
print(summary(anova_result))


