# Load Required Libraries

library(readxl)
library(ggplot2)
library(dplyr)
library(corrplot)
library(lubridate)



# 1. Import Dataset and Basic Exploration

# Import dataset
AirQuality <- read_excel("C:/Users/Patel/OneDrive/Desktop/R/AirQualityUCI.xlsx")

# View column names
colnames(AirQuality)

# Check data structure and data types
str(AirQuality)

# Display first few rows
head(AirQuality)

# Display dataset dimensions
dim(AirQuality)

# Basic descriptive statistics
summary(AirQuality)



# Data Preparation

# Replace -200 values (missing values in this dataset) with NA
AirQuality[AirQuality == -200] <- NA

# Convert Time to character
AirQuality$Time <- format(AirQuality$Time, "%H:%M:%S")

# Create DateTime variable
AirQuality$DateTime <- as.POSIXct(
  paste(AirQuality$Date, AirQuality$Time),
  format="%Y-%m-%d %H:%M:%S"
)

# Remove rows with missing DateTime
AirQuality <- AirQuality %>% filter(!is.na(DateTime))



# 2. Exploratory Visualisation

# Time Series Plot: CO concentration over time
# Time series plots are appropriate for showing trends over time.

ggplot(AirQuality, aes(x = DateTime, y = `CO(GT)`)) +
  geom_line(color = "yellow") +
  labs(title = "Time Trend of CO Concentration",
       x = "Date",
       y = "CO (mg/m^3)") +
  theme_minimal()



# Time Series Plot: NO2 concentration over time
# This helps examine temporal variation in pollutant levels.

ggplot(AirQuality, aes(x = DateTime, y = `NO2(GT)`)) +
  geom_line(color = "cyan") +
  labs(title = "Time Trend of NO2 Concentration",
       x = "Date",
       y = "NO2 (µg/m^3)") +
  theme_minimal()



# Scatterplot: CO vs Temperature
# Scatterplots help identify relationships between pollutants and weather variables.

ggplot(AirQuality, aes(x = T, y = `CO(GT)`)) +
  geom_point(alpha = 0.5) +
  labs(title = "Relationship between CO and Temperature",
       x = "Temperature (°C)",
       y = "CO Concentration") +
  theme_minimal()



# Scatterplot: NO2 vs Relative Humidity

ggplot(AirQuality, aes(x = RH, y = `NO2(GT)`)) +
  geom_point(alpha = 0.5) +
  labs(title = "Relationship between NO2 and Relative Humidity",
       x = "Relative Humidity (%)",
       y = "NO2 Concentration") +
  theme_minimal()



# 3. Correlation Analysis

# Select pollutant variables
pollutants <- AirQuality %>%
  select(`CO(GT)`, `NO2(GT)`, `NOx(GT)`, `C6H6(GT)`)

# Remove rows with NA values
pollutants <- na.omit(pollutants)

# Calculate correlation matrix
cor_matrix <- cor(pollutants)

# Display correlation matrix
cor_matrix



# Visualise correlations using heatmap
corrplot(cor_matrix,
         method = "color",
         type = "upper",
         tl.col = "red",
         addCoef.col = "blue")



# Scatterplot matrix
pairs(pollutants,
      main = "Scatterplot Matrix of Pollutants")



# 4. Hypothesis Testing

# Compare CO levels under high vs low temperature

# Create temperature groups using median split
median_temp <- median(AirQuality$T, na.rm = TRUE)

AirQuality$temp_group <- ifelse(AirQuality$T > median_temp,
                                "High Temp",
                                "Low Temp")

# Hypotheses
# H0: Mean CO levels are equal for high and low temperature conditions
# H1: Mean CO levels differ between temperature conditions

# Perform Welch t-test
t_test_result <- t.test(`CO(GT)` ~ temp_group, data = AirQuality)

# Display test results
t_test_result



# 5. Group Comparison by Season

# Extract month
AirQuality$Month <- month(AirQuality$Date)      

# 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")))

# Convert to factor
AirQuality$Season <- factor(AirQuality$Season,
                            levels = c("Winter","Spring","Summer","Autumn"))

# Check groups
table(AirQuality$Season)



# Hypotheses
# H0: Mean CO levels are equal across seasons
# H1: At least one season has different mean CO levels

# Perform ANOVA
anova_result <- aov(`CO(GT)` ~ Season, data = AirQuality)

# Display results
summary(anova_result)



# Boxplot for seasonal comparison
ggplot(AirQuality, aes(x = Season, y = `CO(GT)`)) +
  geom_boxplot(fill = "lightblue") +
  labs(title = "Seasonal Variation in CO Levels",
       x = "Season",
       y = "CO Concentration") +
  theme_minimal()

