# Author: Lirui Bi
# Student number: 2106257
# Title: Pre-process data and generate graphs
# Time: 01.2022
#--------------------------------------------------------------------
rm(list = ls())
install.packages("rJava")
install.packages("xlsx")
# Question 1
library(xlsx)
# Batch loading of climate datasets (including Swansea and Wuhan)
# Index of the sheet to be read
sheet.index<-1:2 
data<-list()
for(i in sheet.index){
  data[[i]]<- xlsx::read.xlsx("climate.xlsx",
                              sheetIndex=i, 
                              header = T,
                              row.names=1)
}

# Selected Swansea and Wuhan
Swansea <- data[[1]]
Wuhan <- data[[2]]

# Transpose datasets for subsequent merging
Swansea <- as.data.frame(t(Swansea))
Wuhan <- as.data.frame(t(Wuhan))

# Add city as a factor
Swansea$city <- rep(as.factor("Swansea"),12)
Wuhan$city <- rep(as.factor("Wuhan"),12)

# Convert avg. Sun hours (hours) to Avg. Sun hours (hours)
colnames(Wuhan)[7]<-"Avg. Sun hours (hours)" 
colnames(Wuhan)[7]

# Display climateData
climateData <- data.frame(rbind(Swansea, Wuhan))
climateData

# Question 2 
library(tidyverse)

# Filter out Swansea's data for calculation
cumu_swansea <- filter(climateData, city=="Swansea")

# Calculate the accumulated rainfall
cumulativeData1 <- data.frame(cumu_rainfall=cumsum(cumu_swansea$Precipitation...Rainfall.mm))

# Calculate the accumulated sunny hours
cumulativeData1$cumu_sunhours <- cumsum(cumu_swansea$Avg..Sun.hours..hours.)

# Filter out Wuhan's data for calculation
cumu_wuhan <- climateData %>% filter(city=="Wuhan")

# Calculate the accumulated rainfall
cumulativeData2 <- data.frame(cumu_rainfall=cumsum(cumu_wuhan$Precipitation...Rainfall.mm))

# Calculate the accumulated sunny hours
cumulativeData2$cumu_sunhours <- cumsum(cumu_wuhan$Avg..Sun.hours..hours.)

# Merge data from two cities
cumulativeData <- data.frame(rbind(cumulativeData1, cumulativeData2))

# Add a city column
cumulativeData$city <- climateData$city

#Display cumulativeData 
cumulativeData

# Question 3 
# Set up the canvas
par(mfrow=c(1,2))
displayGraph <- function(data, city_name="Swansea", weather_parameter="Humidity...")
{
  # Select the data for the corresponding city
  s_c = data[data$city==city_name,] 
  # Select the climate parameters to be analysed
  p = s_c[weather_parameter] 
  # Corresponding city name as title
  label = city_name 
  plot(p[,1],type="l", xlab = "Monthly", ylab = weather_parameter, main = label)
}
# Humidity of Wuhan
displayGraph(data=climateData, 
             city_name = "Wuhan",
             weather_parameter = "Humidity...")

# Rainfall of Swansea
displayGraph(data = climateData,
             city_name = "Swansea",
             weather_parameter = "Rainy.days..d.")

# Question 4 
compareCities <- function(data, city_name, p1, p2)
{
  # Select the city you want
  s_c = data[data$city==city_name,] 
  # Select another city
  s_c1 = data[data$city!=city_name,] 
  # Given two main climate parameters, mean temperature and humidity
  w1="Avg..Temperature..C" 
  w2="Humidity..." 
  # If the climate parameter does not match one of these two parameters
  if(w1==colnames(data)[p1]&w2==colnames(data)[p2])
    { 
      # The order of corresponding climate parameters
      p_1 = s_c[colnames(data)[p1]] 
      # The name of the corresponding climate parameter as the title
      label11=colnames(data)[p1] 
      plot(p_1[,1], col="red", type="l", ylim = c(3,30), 
           xlab = "Month", ylab= label11, main=label11)
      # Another city's data plotted
      p_2 = s_c1[colnames(data)[p1]] 
      lines(p_2[,1], col="blue", type="l")
      legend("top", pch = c(15,15),
            legend = c("Swansea","Wuhan"), 
            col = c("red","blue"), bty = "n") 
      p_3 = s_c[colnames(data)[p2]]
      label22=colnames(data)[p2]
      plot(p_3[,1],type="l",col="red", ylim = c(0.5,1), 
           xlab = "Month", ylab= label22, main=label22)
      p_4 = s_c1[colnames(data)[p2]]
      lines(p_4[,1], col="blue",type="l")
      legend("top", pch = c(15,15),
             legend = c("Swansea","Wuhan"), 
           col = c("red","blue"), bty = "n")
    } 
  # The rest of the parameters we plot using the barplot function
  else 
    { 
      # The order of corresponding climate parameters
      b_1 = s_c[colnames(climateData)[p1]]
      # The name of the corresponding climate parameter as the title
      label1=colnames(climateData)[p1]
      plot(b_1[,1], col="red", type="l", ylim = c(3,30),
           xlab = "Month", ylab= label1, main=label1)
      # Another city's data plotted
      b_2 = s_c1[colnames(climateData)[p1]]
      lines(b_2[,1], col="blue", type="l")
      legend("top", pch = c(15,15),
             legend = c("Swansea","Wuhan"), 
             col = c("red","blue"), bty = "n") 
      #Extracting the city, month and selected climate information
      City<- data.frame(climateData[,8])
      temp_climate<- data.frame(climateData[,p2])
      Month<- data.frame(rownames(climateData)[1:12])
      temp <- data.frame(cbind(Month, temp_climate, City))
      # The name of the corresponding climate parameter as the climate colname
      label2 = colnames((climateData)[p2])
      colnames(temp)<-c("Month",label2, "City")
      library(ggplot2)
      p <- ggplot(temp,aes(Month,temp[,2], fill=City))
      p+geom_bar(stat = 'identity',position="dodge")
    }
}

compareCities(data=climateData, city_name="Swansea", p1=1, p2=5)
compareCities(data=climateData, city_name="Wuhan", p1=1, p2=7)

