# ================================
# INSTALL REQUIRED PACKAGES (run once if not installed)
# ================================

install.packages("readxl")      # For reading Excel files
install.packages("tidyverse")   # For data manipulation & visualization (ggplot2, dplyr, etc.)
install.packages("corrplot")    # For visualising correlation matrices
install.packages("lubridate")   # For handling date and time data

# ================================
# LOAD LIBRARIES
# ================================

library(readxl)     # Enables importing Excel datasets
library(tidyverse)  # Provides tools for data wrangling and plotting
library(corrplot)   # Used to create correlation heatmaps
library(lubridate)  # Helps extract and manipulate date-time features

# ================================
# TASK 1.1 — IMPORT DATASET AND BASIC EXPLORATION
# ================================

# Import dataset from Excel file into R
AirQuality <- read_excel("AirQualityUCI.xlsx")

# Display first few rows to understand structure and values
head(AirQuality)

# Display column names to know available variables
colnames(AirQuality)

# Show structure of dataset (data types, variables)
str(AirQuality)

# Get dimensions (rows and columns count)
dim(AirQuality)

# Summary statistics (mean, median, min, max, etc.)
summary(AirQuality)

# Replace invalid values (-200 used in dataset as missing values) with NA
AirQuality[AirQuality == -200] <- NA

# Remove rows with missing values to clean dataset
AirQuality <- na.omit(AirQuality)

# Extract month from Date column for seasonal analysis
AirQuality$month <- month(AirQuality$Date)

# Convert Time into standard HH:MM:SS format
AirQuality$Time <- format(AirQuality$Time, "%H:%M:%S")

# Convert Date into standard YYYY-MM-DD format
AirQuality$Date <- format(AirQuality$Date, "%Y-%m-%d")

# Combine Date and Time into a single Datetime column
AirQuality$Datetime <- as.POSIXct(
  paste(AirQuality$Date, AirQuality$Time),
  format = "%Y-%m-%d %H:%M:%S"
)

# View newly created datetime values
head(AirQuality$Datetime)

# ================================
# TASK 1.2 — EXPLORATORY VISUALISATION
# ================================

# Time Series Plot for Carbon Monoxide (CO)
# Purpose: To observe trends and fluctuations over time
ggplot(AirQuality, aes(x = Datetime, y = `CO(GT)`)) +
  geom_line(color = "blue") +
  labs(title = "Carbon Monoxide Concentration Over Time",
       x = "Time",
       y = "CO (mg/m3)")

# Time Series Plot for Nitrogen Dioxide (NO2)
# Purpose: To identify temporal patterns in NO2 levels
ggplot(AirQuality, aes(x = Datetime, y = `NO2(GT)`)) +
  geom_line(color = "red") +
  labs(title = "Nitrogen Dioxide Concentration Over Time",
       x = "Time",
       y = "NO2 (µg/m3)")

# Scatterplot: Humidity vs NO2
# Purpose: To examine relationship between environmental factor (humidity) and pollutant
ggplot(AirQuality, aes(x = RH, y = `NO2(GT)`)) +
  geom_point(color = "purple") +
  labs(title = "Relationship Between Humidity and NO2",
       x = "Relative Humidity (%)",
       y = "NO2 Concentration")

# ================================
# TASK 1.3 — CORRELATION ANALYSIS
# ================================

# Select only pollutant variables for correlation analysis
pollutants <- AirQuality %>%
  select(`CO(GT)`, `NOx(GT)`, `NO2(GT)`, `C6H6(GT)`)

# Compute correlation matrix (relationship strength between variables)
cor_matrix <- cor(pollutants, use = "complete.obs")

# Display correlation values
cor_matrix

# Visualize correlation matrix using heatmap
# Purpose: Quickly identify strong/weak relationships
corrplot(cor_matrix,
         method = "color",
         type = "upper",
         tl.col = "black",
         tl.srt = 45)

# Scatterplot: NOx vs NO2
# Purpose: To visually confirm correlation between these pollutants
ggplot(AirQuality, aes(x = `NOx(GT)`, y = `NO2(GT)`)) +
  geom_point(color = "orange") +
  labs(title = "Relationship Between NOx and NO2",
       x = "NOx",
       y = "NO2")

# ================================
# TASK 1.4 — HYPOTHESIS TESTING
# ================================

# Create temperature groups based on median value
# Purpose: Divide data into High vs Low temperature for comparison
AirQuality$temp_group <- ifelse(AirQuality$T > median(AirQuality$T),
                                "High Temperature",
                                "Low Temperature")

# Perform independent t-test
# Purpose: Check if CO levels differ significantly between temperature groups
t_test_result <- t.test(`CO(GT)` ~ temp_group, data = AirQuality)

# Display test results (p-value, confidence interval, etc.)
t_test_result

# ================================
# TASK 1.5 — SEASONAL GROUP COMPARISON
# ================================

# Extract month again from Datetime (ensures consistency)
AirQuality$month <- month(AirQuality$Datetime)

# Create seasonal categories based on month
# Purpose: Group data into seasons for comparison
AirQuality$season <- ifelse(AirQuality$month %in% c(12,1,2), "Winter",
                            ifelse(AirQuality$month %in% c(3,5), "Spring",
                                   ifelse(AirQuality$month %in% c(4,6,7,8), "Summer",
                                          "Autumn")))

# Boxplot for seasonal NO2 distribution
# Purpose: Compare pollutant levels across seasons
ggplot(AirQuality, aes(x = season, y = `NO2(GT)`, fill = season)) +
  geom_boxplot() +
  labs(title = "Seasonal Distribution of NO2 Levels",
       x = "Season",
       y = "NO2 Concentration")

# Perform ANOVA test
# Purpose: Determine if NO2 levels differ significantly across seasons
anova_result <- aov(`NO2(GT)` ~ season, data = AirQuality)

# Display ANOVA summary results
summary(anova_result)