# Laurice Keogh
# Statistical programming script assignment 2 
# May 2024

# Step 1: Load roller coaster data from CSV file
# create loadDataFile function
loadDataFile <- function() {
  # Load the csv file into a temporary data frame
  tempDataFrame <- read.csv("roller_coasters.csv", header=TRUE, 
                            stringsAsFactors=TRUE)
  
  # Convert specific columns to factors
  tempDataFrame$seating_type <- factor(tempDataFrame$seating_type)
  tempDataFrame$material_type <- factor(tempDataFrame$material_type)
  tempDataFrame$manufacturer <- factor(tempDataFrame$manufacturer)
  tempDataFrame$status <- factor(tempDataFrame$status)
  
  # Return coasterData to the main script
  return(tempDataFrame)
}



# Step 2: Generate data frame for highest operating roller coasters
# Function to generate data frame for highest operating roller coasters by type
generateHighestData <- function(coasterData) {
  
  # Create an empty data frame to store highest operating roller coasters
  highestData <- data.frame()
  
  # Get unique seating types
  unique_types <- unique(coasterData$seating_type)
  
  # Loop through each unique seating type
  for (type in unique_types) {
    
    # Subset data for the current seating type and the status 'status.operating'
    subset_data <- coasterData[coasterData$seating_type == type 
                               & coasterData$status == 'status.operating', ]
    
    # Find the roller coaster with the maximum height in the subset
    max_height_index <- which.max(subset_data$height)
    
    # Extract the roller coaster with the maximum height from the subset
    max_height_coaster <- subset_data[max_height_index, ]
    
    # Extract name, seating_type, height, park, and status columns for
    # highest coaster
    max_height_coaster <- max_height_coaster[c("name", "seating_type", "height",
                                               "park", "status")]
    
    #append the dataframe to include data from max_height_coaster
    highestData <- rbind(highestData, max_height_coaster)
  }
  
  #return the data frame
  return(highestData)
}
  


# Step 3: Display comparison of top 10 fastest inverted roller coasters
displayComparison <- function(seating_type, coasterData) {
  
  # Subset coasterData for roller coasters of the specified seating type that 
  # are operating
  subset_data <- coasterData[coasterData$seating_type == seating_type 
                             & coasterData$status == "status.operating", ]
  
  # Extract the top 10 fastest roller coasters from the subset, ordered by speed
  # [2]
  top_10_fastest <- head(subset_data[order(-subset_data$speed), ], 10)
  
  # Extract roller coaster names
  coaster_names <- top_10_fastest$name
  
  # Extract roller coaster speeds
  coaster_speeds <- top_10_fastest$speed
  
  # Create a barplot displaying the speeds of the top 10 fastest roller coasters
  barplot(coaster_speeds, 
          
          # Set the main title of the plot [2]
          main = paste("Top 10 Fastest", seating_type, "Roller Coasters 
                       (Operating)"),
          
          # Set the label for the x-axis
          xlab = "Roller Coaster Name", 
          
          # Set the label for the y-axis
          ylab = "Speed (mph)",
          
          # Set the color of the bars to skyblue
          col = "skyblue",
          
          # Set the y-axis limits dynamically based on the maximum speed, 
          # with 20% additional space
          ylim = c(0, max(coaster_speeds, na.rm = TRUE) * 1.2),
          
          # Set the names for the bars to coaster_names
          names.arg = coaster_names, cex.names = 0.8)
}



# Step 4: Calculate and store the mean height, length, and correlation of length
# and speed for Sit Down roller coasters
correlateLengthSpeed <- function(coasterData) {
  
  # Filter coasterData for Sit Down roller coasters with [2] no NA fields
  sit_down_data <- coasterData[coasterData$seating_type == "Sit Down" 
                               & complete.cases(coasterData), ]
  
  # Calculate mean height 
  mean_height <- mean(sit_down_data$height)
  
  # Calculate mean length
  mean_length <- mean(sit_down_data$length)
  
  # Calculate correlation coefficient between length and speed [3]
  correlation <- cor(sit_down_data$length, sit_down_data$speed)
  
  # Create a data frame to store the results, and [2] define the column names
  lengthSpeed <- data.frame(mean_height = mean_height, 
                            mean_length = mean_length, 
                            correlation = correlation)
  # Return the data frame
    return(lengthSpeed)
  }
  


# Step 5: Compare wooden and steel roller coasters using t-test
compareWoodenSteel <- function(coasterData) {
  
  # Filter coasterData for wooden roller coasters with [2] no NA fields
  wooden_data <- coasterData[coasterData$material_type == "Wooden"
                             & complete.cases(coasterData), ]
  # Filter coasterData for steel roller coasters with [2] no NA fields
  steel_data <- coasterData[coasterData$material_type == "Steel" 
                            & complete.cases(coasterData), ]
    
  # Perform independent t-test to compare the mean speeds of wooden and steel 
  # roller coasters
  t_test_result <- t.test(wooden_data$speed, steel_data$speed)
  
  # Print the t-test results
  print(t_test_result)
  
  # Print hypotheses and conclusions
  cat("Hypotheses:\n")
  cat("Null Hypothesis (H0): There is no significant difference in the mean 
      speeds of wooden and steel roller coasters.\n")
  cat("Alternative Hypothesis (H1): There is a significant difference in the 
      mean speeds of wooden and steel roller coasters.\n\n")
  cat("T-test results:\n")
  
  # Check significance level
  if (t_test_result$p.value < 0.05) {
      cat("Conclusion: We reject the null hypothesis. There is a significant 
          difference in the mean speeds of wooden and steel roller coasters.\n")
  } else {
      cat("Conclusion: We accept the null hypothesis. There is no significant 
          difference in the mean speeds of wooden and steel roller coasters.\n")
    }
  }
  
  
  
### Main Script:
  
# Step 1: Load roller coaster data from CSV file
coasterData <- loadDataFile()
  
# Step 2: Generate data frame for highest operating roller coasters
highestData <- generateHighestData(coasterData)
  
# Step 3: Display comparison of top 10 fastest inverted roller coasters [2]
displayComparison("Inverted", coasterData)
  
# Step 4: Calculate and store the mean height, length, and correlation of length
# and speed for Sit Down roller coasters
lengthSpeed<-data.frame(correlateLengthSpeed(coasterData)) 
 
# Step 5: Compare wooden and steel roller coasters using t-test
compareWoodenSteel(coasterData)
 