# -----------------------------------------
# AirQualityAnalysis.r
# Author: Mihai - Sergiu Varzare
# Module: ACCA7022 - Advanced Statistical Programming
# Purpose: Analysis of Air Quality Dataset
# Date: March 2026
# -----------------------------------------

# -----------------------------------------
# Load required libraries
# -----------------------------------------
library(ggplot2)
library(corrplot)

# -----------------------------------------
# Load dataset
# -----------------------------------------
AirQuality <- read.csv("AirQualityUCI.csv", sep = ";", dec = ",")

# -----------------------------------------
# Initial data inspection
# -----------------------------------------
head(AirQuality)
str(AirQuality)
summary(AirQuality)
dim(AirQuality)

# -----------------------------------------
# Data Cleaning
# -----------------------------------------

# Remove the last two empty columns
AirQuality <- AirQuality[, -c(16, 17)]

# Replace invalid -200 values with NA
AirQuality[AirQuality == -200] <- NA

# Convert Date column to Date format
AirQuality$Date <- as.Date(AirQuality$Date, format = "%d/%m/%Y")

# Convert Time column to time format
AirQuality$Time <- strptime(AirQuality$Time, format = "%H.%M.%S")

# Check cleaned data
summary(AirQuality)

# Note:
# The dataset contains -200 values representing missing data.
# These were replaced with NA to ensure accurate statistical analysis.
# Additionally, the final two empty columns were removed to improve data quality.

# -----------------------------------------
# Exploratory Visualisation
# -----------------------------------------

# Time series plot of CO levels over time
ggplot(AirQuality, aes(x = Date, y = CO.GT.)) +
  geom_line(color = "blue") +
  labs(title = "CO Levels Over Time",
       x = "Date",
       y = "CO Concentration") +
  theme_minimal()

# This time series plot is used to analyse trends in CO levels over time.
# It helps identify patterns such as fluctuations, peaks, and possible seasonal behaviour.
# Missing values are automatically excluded from the plot.

# Scatterplot of CO vs Temperature
ggplot(AirQuality, aes(x = T, y = CO.GT.)) +
  geom_point(color = "red", alpha = 0.5) +
  labs(title = "CO vs Temperature",
       x = "Temperature",
       y = "CO Concentration") +
  theme_minimal()

# This scatterplot is used to examine the relationship between temperature and CO levels.
# It helps identify whether temperature has an influence on pollution levels.
# Some observations were removed automatically because they contained missing values.

# -----------------------------------------
# Correlation Analysis
# -----------------------------------------

# Select pollutant variables
pollutants <- AirQuality[, c("CO.GT.", "NO2.GT.", "NOx.GT.", "C6H6.GT.")]

# Summary of selected pollutants
summary(pollutants)

# Calculate Pearson correlation matrix using complete observations only
cor_matrix <- cor(pollutants, use = "complete.obs")

# Display correlation matrix
cor_matrix

# Pearson correlation was used to measure the strength and direction of
# linear relationships between selected pollutants.
# The option use = "complete.obs" ensures that only complete cases are analysed.

# Correlation heatmap
corrplot(cor_matrix, method = "color", type = "upper", addCoef.col = "black")

# A correlation heatmap was chosen because it provides a clear visual summary
# of the relationships between multiple pollutants at the same time.

# Scatterplot of NOx vs NO2
ggplot(AirQuality, aes(x = NOx.GT., y = NO2.GT.)) +
  geom_point(color = "darkgreen", alpha = 0.5) +
  labs(title = "Relationship between NOx and NO2",
       x = "NOx Concentration",
       y = "NO2 Concentration") +
  theme_minimal()

# This scatterplot was selected to explore the relationship between NOx and NO2,
# as both are traffic-related pollutants and may show a positive association.

# -----------------------------------------
# Hypothesis Testing: CO levels under high vs low temperature
# -----------------------------------------

# Create temperature groups using the median temperature
median_temp <- median(AirQuality$T, na.rm = TRUE)

AirQuality$temp_group <- ifelse(AirQuality$T <= median_temp,
                                "Low Temperature",
                                "High Temperature")

# Check the number of observations in each group
table(AirQuality$temp_group)

# Boxplot for visual comparison
ggplot(AirQuality[!is.na(AirQuality$temp_group), ],
       aes(x = temp_group, y = CO.GT., fill = temp_group)) +
  geom_boxplot() +
  labs(title = "CO Levels by Temperature Group",
       x = "Temperature Group",
       y = "CO Concentration") +
  theme_minimal()

# Perform independent samples t-test
t_test_result <- t.test(CO.GT. ~ temp_group, data = AirQuality)
t_test_result

# Null hypothesis (H0):
# There is no significant difference in CO levels between low and high temperature groups.

# Alternative hypothesis (H1):
# There is a significant difference in CO levels between low and high temperature groups.

# A t-test was used because it compares the mean CO concentration between two independent groups.

# Interpretation:
# The p-value is greater than 0.05, indicating that there is no statistically
# significant difference in CO levels between high and low temperature groups.
# Therefore, we fail to reject the null hypothesis.

# -----------------------------------------
# Seasonal Analysis
# -----------------------------------------

# Extract month from Date
AirQuality$Month <- as.numeric(format(AirQuality$Date, "%m"))

# Create Season variable
AirQuality$Season <- ifelse(AirQuality$Month %in% c(12, 1, 2), "Winter",
                            ifelse(AirQuality$Month %in% c(3, 4, 5), "Spring",
                                   ifelse(AirQuality$Month %in% c(6, 7, 8), "Summer", "Autumn")))

# Check season counts
table(AirQuality$Season)

# Boxplot of CO levels across seasons
ggplot(AirQuality, aes(x = Season, y = CO.GT., fill = Season)) +
  geom_boxplot() +
  labs(title = "CO Levels Across Seasons",
       x = "Season",
       y = "CO Concentration") +
  theme_minimal()

# This boxplot compares CO levels across seasons.
# It helps identify whether pollution varies throughout the year.

# Perform ANOVA
anova_result <- aov(CO.GT. ~ Season, data = AirQuality)
summary(anova_result)

# Null hypothesis (H0):
# There is no significant difference in CO levels across seasons.

# Alternative hypothesis (H1):
# There is a significant difference in CO levels across seasons.

# Interpretation:
# The p-value is less than 0.05, indicating that there is a statistically
# significant difference in CO levels across seasons.
# Therefore, the null hypothesis is rejected, and we conclude that seasonal
# variation has a significant effect on CO concentration levels.