#Check to see if packages are already installed
#if packages are not installed - install packages
if (!require("rstudioapi")) {
  install.packages("rstudioapi")
}
if (!require("ggplot2")) {
  install.packages("ggplot2")
}

#import libraries
library(rstudioapi)
library(ggplot2)

#get the current path of the working directory 
#this is to ensure that the data file and script are in the same folder path
current_path = rstudioapi::getActiveDocumentContext()$path 

#set working directory to the current path
setwd(dirname(current_path))

#Task 1

#####################################################################
#   Task 1.1                                                        #
#   - Check roller_coaster.csv exists in working directory          #
#   - if file does not exist print warning and break to prevent     # 
#      to following script from executing                           #
#   - if file exists:                                               #
#       - read csv into a dataframe named 'coasterData'             #
#       - ensuring that headers are imported using 'header=T'       #
#       - ensure that material_type, seating_type, manufacturer,    #
#           and status are imported as factors                      #
#       - print 'coasterData' dataframe                             #
#####################################################################

if(!file.exists("roller_coasters.csv")) {
  print("No CSV file found")
  break
} else {
  coasterData <- data.frame(read.csv("roller_coasters.csv",header=T, colClasses=c(material_type="factor",seating_type="factor",manufacturer="factor",status="factor")))
  coasterData
}

#####################################################################
#   Task 1.2                                                        #
#   - Create function that orders a dataframe by height and returns #
#       the top n records                                           #
#   - create dataframe called 'heighestData' based on material_type #
#   - use top_n_records function to return highest coaster for each #
#        material_type                                              #
#   - n = 1 denotes top record for each category                    #
#   - return columns name,height,park, and status using [] to       #
#       specify the returned columns                                #
#   - return dataframe named 'highestDate'                          #
#####################################################################

#Top N records function - input values = dataframe and the amount of records to be returned
top_n_records <- function(df, n) {
  df[order(df$height, decreasing = TRUE), ][1:n, ]
}

#creating dataframe to return top record for each material_type by height
highestData <- data.frame(do.call(rbind, by(coasterData, coasterData$material_type, top_n_records, n=1)))[c('name','height','park','status')]

#return dataframe
highestData

#####################################################################
#   Task 1.3                                                        #
#     - create function that will display a bar chart showing the   #
#         top 10 roller coasters, by speed, where the steating_type #
#          is 'inverted'                                            #
#     - filter dataframe based on the seating_type that is passed   #
#         into the function                                         #
#     - filter dataframe to show the top 10 speeds                  #
#     - use ggplot to plot a box plot with speed as the X axis and  #
#         name as the Y axis                                        #
#     - style the box plot using the ggplot pre-defined functions   #
#     - dynamically set the sub heading using the variable passed   #
#         into the function                                         #
#####################################################################

#define function called 'displayComparison' with the dataframe and seating_type as variables
displayComparison <- function(df,seating_type) {
  #filter dataframe based on seatring type
  df <- df[df$seating_type==seating_type,]
  #filer dataframe to top 10 decreasing to return the highest speeds
  df <- df[order(df$speed, decreasing = TRUE), ][1:10, ]
  #use ggplot to plot bar chart
  ggplot(
    #input dataframe
    data=df, 
      #define the column names used for the box chart
      aes(x=speed,y=reorder(name,speed))
    ) +
    # define style and colour theme of the boxplot
    geom_bar(
      stat="identity",fill="steelblue"
    )+
    # style the labels and text colour and size
    geom_text(
      aes(label=speed),vjust=0.5, hjust=1.25, color="white",  size=3.5
    )+
    # define label text with dynamic subtitle
    labs(
      title="Top 10 Roller Coasters by speed \n where the seat type is:",
      subtitle=seating_type,
      x="Speed",
      y="Roller Coaster"
    )+
    # futher theme styling for labels and titles
    theme(
      plot.title = element_text(color="Black", size=12, face="bold", hjust=0.5),
      plot.subtitle = element_text(color="red",size=14,face="bold",hjust=0.5),
      axis.title.x = element_text(color="#993333", size=12),
      axis.title.y = element_text(color="#993333", size=12)
    )
}
#run the function with coasterData and "inverted" as variables
displayComparison(coasterData,"Inverted")

#####################################################################
#   Task 1.4                                                        #
#     - create function 'correlateLengthSpeed' that takes a         #
#         dataframe as a variable                                   #
#     - filter dataframe where the type is equal to 'Sit Down'      #
#     - return a dataframe the shows mean height and length and the #
#         correlation between of speed and height                   #
#     - ensure that there is no NA values in each field             #
#####################################################################

# define function that accepts a dataframe a a variable
correlateLengthSpeed <- function(df) {
  #filter dataframe based on the type of coaster as 'Sit Down'
  sit_down_coasters <- df[df$seating_type == 'Sit Down',]
  #return dataframe
  return(
    data.frame
      (
        # calculate the mean height based on the height column with no NA's
        Mean_Height = mean(sit_down_coasters[!is.na(sit_down_coasters$height),]$height),
        # calculate the mean length based on the length column with no NA's
        Mean_Length = mean(sit_down_coasters[!is.na(sit_down_coasters$length),]$length),
        # use cor function in R to calculate the correlation between length and speed
        # use 'pariwise.complete.obs' to remove any NA pairs within the column values
        Correlation_Length_Speed = cor(sit_down_coasters$length, sit_down_coasters$speed, use="pairwise.complete.obs")
     )
    )

}

# run 'correlateLengthSpeed' function with coasterData as a variable
correlateLengthSpeed(coasterData)

#####################################################################
#   Task 1.5                                                        #
#     - create function called 'compareWoodenSteal' tha accepts     #
#         a dataframe as a variable                                 #
#     - perform a T-test function to produce a p-level value        #
#     - compare the results from the T-Test to find any significance#
#         at a level of 0.05                                        #
#     - use var.equal = FALSE to show unequal variance between the  #
#          two columns                                              #
#####################################################################

# define 'compareWoodenSteel' function that accepts a dataframe variable
compareWoodenSteel <- function(df) {     
  # if statement to compare the results of the t-test over or under 0.05
  if(
      # use in-built R function for t-test
      t.test(
        # define the columns that will be compared - speed and type
        speed ~ type,
        # input data for the t-test
        data = 
          # omit any NA values within the data
          na.omit(
            data.frame( 
              # define the type column with values steel and wooden
              type = rep(c("Steel", "Wooden")),
              # define the speed column isolating the columns from the dataframe
              speed = c(df[df$material_type=="Steel",]$speed,df[df$material_type=="Wooden",]$speed)
            )
          ),
        # set var.equal to false as unequal variance 
        var.equal=FALSE
      # return the p.value from the t-test
      )$p.value 
    # compare the p.value to 0.05
    <= 0.05) {
    # if p.value is less than or equal to 0.05 return 'Significant Difference'
    result <- "Significant Difference"
  } else {
    # if p.value is greaterthan 0.05 return 'No Significant Difference'
    result <- "No Significant Difference"
  }
  return(result)
}

# run 'compareWoodenSteal' function with coasterData as a variable
compareWoodenSteel(coasterData)
