# Yufei Tang
# climatewales
# data analysis
# 11.01.2024


# Import necessary libraries
library(readxl)
library(dplyr)
library(ggplot2)
library(tidyr)

# Read data from the Excel file
data <- read_excel("C:/Users/tyf/Desktop/Wales_Climate_Data.xlsx")

# Task 1: Calculate and visualize the decadal average of summer temperature from 1892 to 2022
# as summer usually has the highest temperature in a year, so I choose summer to finish this task
data %>%
  filter(year >= 1892 & year <= 2022) %>%  # Filter data for the years 1892-2022
  mutate(decade = floor((year - 1892) / 10) * 10 + 1892) %>%  # Calculate the starting year of each decade
  group_by(decade) %>%  # Group data by decade
  summarize(average_summer_temp = mean(sum, na.rm = TRUE)) %>%  # Calculate the average summer temperature per decade
  ggplot(aes(x = decade, y = average_summer_temp)) +  # Plot the data
  geom_line() +  # Use a line graph
  labs(title = "Decadal Average of Summer Temperature (1892-2022)",
       x = "Decade",
       y = "Average Summer Temperature")
# Task 2: Compute the correlation between annual rainfall days and summer temperature
correlation_result <- cor.test(data$ann, data$sum, 
                               method = "pearson", use = "complete.obs")  # Perform Pearson's correlation test
print(correlation_result)  # Print the result
# Task 3: Perform a t-test to compare August temperatures between 1890-1910 and 2000-2020
temp_early <- filter(data, year >= 1890 & year <= 1910)$aug  # Filter data for early period
temp_late <- filter(data, year >= 2000 & year <= 2020)$aug  # Filter data for later period
t_test_result <- t.test(temp_early, temp_late)  # Apply t-test
print(t_test_result)  # Print the t-test result
# Task 4: Perform ANOVA to check for significant differences in annual rainy days across decades
data %>%
  filter(year >= 1891 & year <= 2020) %>%
  mutate(decade = floor((year - 1891) / 10) * 10 + 1891) %>%
  group_by(decade) %>%
  summarize(avg_annual_rainfall = mean(ann, na.rm = TRUE)) %>%
  aov(avg_annual_rainfall ~ decade, data = .) %>%
  summary() %>%
  print()
