# 1. Import Dataset and Initial Exploration
# Clear workspace
rm(list = ls())

# Import the dataset
AirQuality <- read.csv("C:/Users/user/Downloads/Port_Talbot_Hourly_AQ.csv",
                       header = TRUE,
                       stringsAsFactors = FALSE,
                       na.strings = "No data")

# Check column names
cat("Column Names:\n")
colnames(AirQuality)

# Check data types
cat("\nData Types:\n")
str(AirQuality)

# Display the first six rows
cat("\nFirst Six Rows:\n")
head(AirQuality)

# Display dataset dimensions
cat("\nDataset Dimensions:\n")
dim(AirQuality)

cat("\nNumber of Rows:\n")
nrow(AirQuality)

cat("\nNumber of Columns:\n")
ncol(AirQuality)

# Display basic descriptive statistics
cat("\nSummary Statistics:\n")
summary(AirQuality)

# Count missing values in each column
cat("\nMissing Values in Each Column:\n")
colSums(is.na(AirQuality))




# 2. Exploratory Data Visualisation
# Load required packages
library(ggplot2)
library(dplyr)

# Convert Date column to Date format
AirQuality$Date <- as.Date(AirQuality$Date, format = "%d/%m/%Y")

# Convert pollutant and weather variables to numeric
AirQuality$Ozone <- as.numeric(AirQuality$Ozone)
AirQuality$Nitrogen.dioxide <- as.numeric(AirQuality$Nitrogen.dioxide)
AirQuality$PM2.5.particulate.matter..Hourly.measured. <- as.numeric(AirQuality$PM2.5.particulate.matter..Hourly.measured.)
AirQuality$Modelled.Wind.Speed <- as.numeric(AirQuality$Modelled.Wind.Speed)
AirQuality$Modelled.Temperature <- as.numeric(AirQuality$Modelled.Temperature)

# Remove rows containing missing values
AirQuality_clean <- na.omit(AirQuality)

# Time Series Plot for Ozone
# A time series plot is used to examine how ozone levels change over time.
ggplot(AirQuality_clean, aes(x = Date, y = Ozone)) +
  geom_line(color = "blue") +
  labs(title = "Time Trend of Ozone",
       x = "Date",
       y = "Ozone") +
  theme_minimal()

# Time Series Plot for PM2.5
# A time series plot helps identify seasonal and long-term trends in PM2.5.
ggplot(AirQuality_clean,
       aes(x = Date,
           y = PM2.5.particulate.matter..Hourly.measured.)) +
  geom_line(color = "red") +
  labs(title = "Time Trend of PM2.5",
       x = "Date",
       y = "PM2.5") +
  theme_minimal()

# Scatterplot: PM2.5 vs Wind Speed
# Scatterplots are used to examine the relationship between pollutant levels and weather variables.
ggplot(AirQuality_clean,
       aes(x = Modelled.Wind.Speed,
           y = PM2.5.particulate.matter..Hourly.measured.)) +
  geom_point(alpha = 0.4, color = "darkgreen") +
  geom_smooth(method = "lm", se = FALSE, color = "black") +
  labs(title = "PM2.5 vs Wind Speed",
       x = "Wind Speed",
       y = "PM2.5") +
  theme_minimal()

# Scatterplot: Ozone vs Temperature
# This plot explores whether ozone concentration changes with temperature.
ggplot(AirQuality_clean,
       aes(x = Modelled.Temperature,
           y = Ozone)) +
  geom_point(alpha = 0.4, color = "purple") +
  geom_smooth(method = "lm", se = FALSE, color = "black") +
  labs(title = "Ozone vs Temperature",
       x = "Temperature",
       y = "Ozone") +
  theme_minimal()

# Boxplot: Ozone Distribution
# A boxplot is used to visualise the distribution, spread and potential outliers of ozone levels.
ggplot(AirQuality_clean,
       aes(y = Ozone)) +
  geom_boxplot(fill = "lightblue") +
  labs(title = "Distribution of Ozone",
       y = "Ozone") +
  theme_minimal()

# Boxplot: PM2.5 Distribution
# This boxplot shows the spread and possible extreme values of PM2.5 concentrations.
ggplot(AirQuality_clean,
       aes(y = PM2.5.particulate.matter..Hourly.measured.)) +
  geom_boxplot(fill = "lightgreen") +
  labs(title = "Distribution of PM2.5",
       y = "PM2.5") +
  theme_minimal()



# 3. Correlation Analysis Between Pollutants

# Load required packages
library(corrplot)
library(ggplot2)

# Select pollutant variables
pollutants <- AirQuality_clean[, c("Ozone",
                                   "Nitrogen.dioxide",
                                   "Sulphur.dioxide",
                                   "PM2.5.particulate.matter..Hourly.measured.")]

# Calculate Pearson correlation matrix
correlation_matrix <- cor(pollutants,
                          use = "complete.obs",
                          method = "pearson")

# Display the correlation matrix
print(correlation_matrix)

# Visualise the correlation matrix using a correlogram
# Select pollutant variables
pollutants <- AirQuality_clean[, c(
  "Ozone",
  "Nitrogen.dioxide",
  "Sulphur.dioxide",
  "PM2.5.particulate.matter..Hourly.measured."
)]

# Rename variables for better visualisation
colnames(pollutants) <- c(
  "Ozone",
  "NO2",
  "SO2",
  "PM2.5"
)

# Calculate correlation matrix
correlation_matrix <- cor(
  pollutants,
  use = "complete.obs",
  method = "pearson"
)

# Load package
library(corrplot)

# Create a clear correlogram
corrplot(
  correlation_matrix,
  method = "color",
  type = "upper",
  order = "hclust",
  addCoef.col = "black",
  number.cex = 0.8,
  tl.col = "black",
  tl.cex = 1,
  tl.srt = 0,
  diag = FALSE,
  mar = c(1, 1, 2, 1),
  title = "Correlation Matrix of Air Pollutants"
)

# Scatterplot: Ozone vs Nitrogen Dioxide
# Scatterplots help visualise the relationship between two pollutants.
ggplot(AirQuality_clean,
       aes(x = Ozone,
           y = Nitrogen.dioxide)) +
  geom_point(alpha = 0.4, colour = "blue") +
  geom_smooth(method = "lm",
              se = FALSE,
              colour = "red") +
  labs(title = "Relationship Between Ozone and Nitrogen Dioxide",
       x = "Ozone",
       y = "Nitrogen Dioxide") +
  theme_minimal()

# Scatterplot: PM2.5 vs Sulphur Dioxide
# This plot examines whether PM2.5 concentrations are associated with sulphur dioxide levels.
ggplot(AirQuality_clean,
       aes(x = PM2.5.particulate.matter..Hourly.measured.,
           y = Sulphur.dioxide)) +
  geom_point(alpha = 0.4,
             colour = "darkgreen") +
  geom_smooth(method = "lm",
              se = FALSE,
              colour = "red") +
  labs(title = "Relationship Between PM2.5 and Sulphur Dioxide",
       x = "PM2.5",
       y = "Sulphur Dioxide") +
  theme_minimal()

# Scatterplot: Ozone vs PM2.5
# This scatterplot explores the relationship between ozone and PM2.5 concentrations.
ggplot(AirQuality_clean,
       aes(x = Ozone,
           y = PM2.5.particulate.matter..Hourly.measured.)) +
  geom_point(alpha = 0.4,
             colour = "purple") +
  geom_smooth(method = "lm",
              se = FALSE,
              colour = "red") +
  labs(title = "Relationship Between Ozone and PM2.5",
       x = "Ozone",
       y = "PM2.5") +
  theme_minimal()


# 4. Hypothesis Testing

# Null Hypothesis (H0):
# There is no significant difference in PM2.5 concentrations
# between high and low wind speed conditions.

# Alternative Hypothesis (H1):
# There is a significant difference in PM2.5 concentrations
# between high and low wind speed conditions.

# Create wind speed groups
median_wind <- median(AirQuality_clean$Modelled.Wind.Speed, na.rm = TRUE)

AirQuality_clean$Wind_Group <- ifelse(
  AirQuality_clean$Modelled.Wind.Speed >= median_wind,
  "High Wind Speed",
  "Low Wind Speed"
)

AirQuality_clean$Wind_Group <- as.factor(AirQuality_clean$Wind_Group)

# Perform Welch's Independent Samples t-test
t_test_result <- t.test(
  PM2.5.particulate.matter..Hourly.measured. ~ Wind_Group,
  data = AirQuality_clean,
  var.equal = FALSE
)

# Display results
print(t_test_result)

# Boxplot
library(ggplot2)

ggplot(AirQuality_clean,
       aes(x = Wind_Group,
           y = PM2.5.particulate.matter..Hourly.measured.,
           fill = Wind_Group)) +
  geom_boxplot() +
  labs(
    title = "PM2.5 Levels by Wind Speed Group",
    x = "Wind Speed Group",
    y = "PM2.5"
  ) +
  theme_minimal() +
  theme(legend.position = "none")



# 5. Group Comparison Across Seasons

# Null Hypothesis (H0):
# There is no significant difference in PM2.5 concentrations
# across Winter, Spring, Summer and Autumn.

# Alternative Hypothesis (H1):
# At least one season has a significantly different mean
# PM2.5 concentration.

# Extract month from the Date column
AirQuality_clean$Month <- as.numeric(format(AirQuality_clean$Date, "%m"))

# Create Season variable
AirQuality_clean$Season <- ifelse(
  AirQuality_clean$Month %in% c(12, 1, 2), "Winter",
  ifelse(
    AirQuality_clean$Month %in% c(3, 4, 5), "Spring",
    ifelse(
      AirQuality_clean$Month %in% c(6, 7, 8), "Summer",
      "Autumn"
    )
  )
)

# Convert Season to a factor
AirQuality_clean$Season <- factor(
  AirQuality_clean$Season,
  levels = c("Winter", "Spring", "Summer", "Autumn")
)

# Perform One-Way ANOVA
anova_result <- aov(
  PM2.5.particulate.matter..Hourly.measured. ~ Season,
  data = AirQuality_clean
)

# Display ANOVA table
summary(anova_result)

# Perform Tukey's Post Hoc Test
tukey_result <- TukeyHSD(anova_result)

# Display Tukey test results
print(tukey_result)

# Boxplot showing PM2.5 concentrations across seasons
library(ggplot2)

ggplot(
  AirQuality_clean,
  aes(
    x = Season,
    y = PM2.5.particulate.matter..Hourly.measured.,
    fill = Season
  )
) +
  geom_boxplot() +
  labs(
    title = "PM2.5 Concentrations Across Seasons",
    x = "Season",
    y = "PM2.5"
  ) +
  theme_minimal() +
  theme(legend.position = "none")




