###### Osvaldas Stanelis 1802408
### Assignment 2 rollercoaster.r

## TASK 1

# Load data file into data frame coasterData

  coasterData<-read.csv("roller_coasters.csv", header=TRUE,
                      stringsAsFactors = FALSE)

# Convert material, manufacturer and current status columns to factors

  coasterData$material_type<-factor(coasterData$material_type)
  coasterData$manufacturer<-factor(coasterData$manufacturer)
  coasterData$status<-factor(coasterData$status)

# Display data frame coasterData
  coasterData

## TASK 2

# Function to find the highest operating roller coaster for each material type
  findHighestCoastersByMaterial<-function(df) {
# Validate the presence of required columns
  requiredColumns<-c("name","height","park","status","material_type")
  if (!all(requiredColumns %in% names(df))) {
    stop("One or more required columns are missing")
  }
# Filter for operating coasters
  operatingCoasters<-df[df$status == "status.operating", requiredColumns]
# Check if any coasters are operating
  if (nrow(operatingCoasters) == 0) {
    stop("No operating coasters found")
  }
  
# Get unique materials
  
  materials<-unique(operatingCoasters$material_type)
  
# Initialize an empty data frame to store the results

  highestData<-data.frame()

# Loop through each material type to find the highest coaster

  for (material in materials) {
    subset<-operatingCoasters[operatingCoasters$material_type == material,]
    if (nrow(subset) > 0) {
      highestCoaster<-subset[which.max(subset$height),]
      highestData<-rbind(highestData, highestCoaster)
    }
  }
  
# Return the data frame containing the highest coaster for each material type
  
  return(highestData)
  }

# Find the highest operating coaster for each material type

  highestData<-findHighestCoastersByMaterial(coasterData)

# Print the resulting data frame

  print(highestData)

## TASK 3

# Function to display speed comparison of the top ten fastest operating roller coasters for a given seating type

  displayComparison<-function(seating_type) {
# Validate the presence of required columns
  requiredColumns<-c("name","speed","status","seating_type")
  if (!all(requiredColumns %in% names(coasterData))) {
    stop("One or more required columns are missing")
  }
  
# Filter for operating coasters of the given seating type
  relevantCoasters<-coasterData[coasterData$status == "status.operating" & 
                                    coasterData$seating_type == seating_type,]
  
# Check if there are enough coasters of the specified seating type
  if (nrow(relevantCoasters) == 0) {
    stop("No operating coasters found for the specified seating type")
  }
  
# Sort by speed and select the top ten fastest
  topCoasters<-relevantCoasters[order(-relevantCoasters$speed),][1:10,]
  
# Check if there are enough coasters to display
  if (nrow(topCoasters) < 1) {
    stop("Not enough coasters to display")
  }
  
# Create a bar chart of the speeds
  barplot(topCoasters$speed, names.arg=topCoasters$name, las=2, 
          main=paste("Top 10 Fastest Operating Roller Coasters -", seating_type),
          xlab="Roller Coaster Name",
          ylab="Speed",
          col="blue",
          border="red")
  }

# Display comparison for 'Inverted' seating type
  displayComparison("Inverted")

## TASK 4

# Function to calculate mean height, mean length, and correlation of length and speed
  correlateLengthSpeed<-function() {
# Filter coasterData for "Sit Down" roller coasters with no NA in height, length, or speed
  filteredData<-coasterData[coasterData$seating_type == "Sit Down" & 
                                !is.na(coasterData$height)& 
                                !is.na(coasterData$length)& 
                                !is.na(coasterData$speed),]
  
  # Check if there are enough coasters to perform analysis
  if (nrow(filteredData) == 0) {
    stop("No suitable records found to perform correlation analysis")
  }
  
  # Calculate mean height and mean length
  meanHeight<-mean(filteredData$height)
  meanLength<-mean(filteredData$length)
  
  # Calculate the correlation coefficient between length and speed
  correlationCoefficient<-cor(filteredData$length, filteredData$speed)
  
  # Create a data frame to store these values
  lengthSpeed<-data.frame(
    Mean_Height=meanHeight,
    Mean_Length=meanLength,
    Correlation_Length_Speed=correlationCoefficient)
  
  # Return the data frame
  return(lengthSpeed)
  }

# Execute the function and store the result in a variable
  lengthSpeedData<-correlateLengthSpeed()

# Print the resulting data frame
  print(lengthSpeedData)

## TASK 5

# Function to perform a t-test to compare the speeds of wooden and steel roller coasters
  compareWoodenSteel<-function() {
# Filter coasterData for wooden and steel roller coasters with no NA in speed
  woodenCoasters<-coasterData[coasterData$material_type == "Wooden" &
                                !is.na(coasterData$speed), "speed"]
  steelCoasters<-coasterData[coasterData$material_type == "Steel" &
                               !is.na(coasterData$speed), "speed"]
  
# Check if there are enough coasters to perform analysis
  if (length(woodenCoasters) == 0 || length(steelCoasters) == 0) {
    stop("Not enough data to perform t-test for one or both coaster types.")
  }
  
# Perform the T-test
  testResult<-t.test(woodenCoasters, steelCoasters,
                     alternative="two.sided", conf.level=0.95)
  
# Print the hypotheses and conclusion
  cat("H0: There is no difference in the mean speeds of wooden and steel roller coasters.\n")
  cat("H1: There is a difference in the mean speeds of wooden and steel roller coasters.\n\n")
  cat("T-test results:\n")
  print(testResult)
  
# Interpret the results
  if (testResult$p.value <= 0.05) {
    cat("\nConclusion: Reject H0. There is a statistically significant difference in the speeds of wooden and steel roller coasters at the p = 0.05 level.\n")
  } else {
    cat("\nConclusion: Do not reject H0. There is no statistically significant difference in the speeds of wooden and steel roller coasters at the p = 0.05 level.\n")
  }
  }

# Call the function to perform the analysis
  compareWoodenSteel()