#Name:NAVEEN DANDLA
#Student Number:2406062
#QUESTION 1:
# Load the data
file_name <- "Life Expectancy.csv"
lifeData <- read.csv(file_name, header = TRUE)

# Convert relevant columns to factors
lifeData$Continent <- as.factor(lifeData$Continent)
lifeData$Hemisphere <- as.factor(lifeData$Hemisphere)
lifeData$Human.Development.Groups <- as.factor(lifeData$Human.Development.Groups)

# Display the resulting data frame
print(head(lifeData))

#QUESTION 2:
# Select columns for years divisible by 5
years_divisible_by_5 <- grep("1995|2000|2005|2010|2015|2020", names(lifeData), value = TRUE)

# Calculate the mean life expectancy for each continent
continentData <- aggregate(
  . ~ Continent,
  data = lifeData[, c("Continent", years_divisible_by_5)],
  FUN = function(x) mean(as.numeric(x), na.rm = TRUE)
)

# Display the resulting data frame
print(continentData)

#QUESTION 3&6:
# Define the function to calculate correlation
HDIRankCorrelation <- function(data) {
  # Extract relevant columns
  hdi_rank <- as.numeric(data$HDI.Rank..2021.)
  life_expectancy_2021 <- as.numeric(data$Life.Expectancy.at.Birth..2021.)
  
  # Calculate correlation
  correlation <- cor(hdi_rank, life_expectancy_2021, use = "complete.obs", method = "pearson")
  
  return(correlation)
}

# Call the function and display the result
correlation_result <- HDIRankCorrelation(lifeData)
cat("Correlation between HDI Rank and Life Expectancy in 2021:", correlation_result, "\n")

#QUESTION 4:
# Define the function to display the graph
displayGraph <- function(data, country, start_year, end_year) {
  # Extract relevant rows and columns
  country_data <- subset(data, Country == country)
  
  # Extract years and filter columns
  year_columns <- grep(paste0("Life.Expectancy.at.Birth..", start_year:end_year, collapse = "|"), 
                       names(country_data), value = TRUE)
  
  # Create a data frame for plotting
  years <- as.numeric(sub("Life.Expectancy.at.Birth..", "", year_columns))
  life_expectancies <- as.numeric(country_data[1, year_columns])
  
  # Plot the graph using base R
  plot(years, life_expectancies, type = "o", col = "orange", pch = 16, lwd = 2,
       xlab = "Year", ylab = "Life Expectancy",
       main = paste("Change in Life Expectancy for", country))
  grid()
}

# Call the function to display the graph for Australia (1995-2020)
displayGraph(lifeData, "Australia", 1995, 2020)

#QUESTION 5:
# Define the function to compare countries
compareCountries <- function(data, start_year, end_year, countries) {
  # Extract years of interest
  year_columns <- grep(paste0("Life.Expectancy.at.Birth..", start_year:end_year, collapse = "|"), 
                       names(data), value = TRUE)
  
  # Create an empty plot
  plot(NULL, xlim = c(start_year, end_year), ylim = c(40, 90), 
       xlab = "Year", ylab = "Life Expectancy", 
       main = "Comparison of Life Expectancy")
  grid()
  
  # Colors for lines
  colors <- rainbow(length(countries))
  
  # Add lines for each country
  for (i in seq_along(countries)) {
    country_data <- subset(data, Country == countries[i])
    if (nrow(country_data) > 0) {
      years <- as.numeric(sub("Life.Expectancy.at.Birth..", "", year_columns))
      life_expectancies <- as.numeric(country_data[1, year_columns])
      lines(years, life_expectancies, type = "o", col = colors[i], lwd = 2, pch = 16)
    }
  }
  
  # Add legend
  legend("bottomright", legend = countries, col = colors, lty = 1, pch = 16, cex = 0.8)
}

# Call the function with sample data
compareCountries(lifeData, 2000, 2020, c("Australia", "India", "United States", "China", "Germany", "Brazil"))

#QUESTION 7:
# Perform a t-test to compare life expectancy in 1990 and 2020
performTTest <- function(data) {
  # Extract life expectancy data for 1990 and 2020
  life_1990 <- as.numeric(data$Life.Expectancy.at.Birth..1990.)
  life_2020 <- as.numeric(data$Life.Expectancy.at.Birth..2020.)
  
  # Perform the t-test
  t_test_result <- t.test(life_1990, life_2020, paired = TRUE, alternative = "two.sided")
  
  # Display hypotheses
  cat("Null Hypothesis (H0): There is no significant difference in life expectancy between 1990 and 2020.\n")
  cat("Alternative Hypothesis (H1): There is a significant difference in life expectancy between 1990 and 2020.\n\n")
  
  # Display the result
  print(t_test_result)
  
  # Decision
  if (t_test_result$p.value < 0.05) {
    cat("\nResult: Reject the null hypothesis. There is a significant difference in life expectancy.\n")
  } else {
    cat("\nResult: Fail to reject the null hypothesis. No significant difference in life expectancy.\n")
  }
}

# Call the function to perform the t-test
performTTest(lifeData)

#QUESTION 8:
# Perform ANOVA to check for differences in life expectancy by continent in 2010
performANOVA <- function(data) {
  # Filter relevant columns
  life_2010 <- as.numeric(data$Life.Expectancy.at.Birth..2010.)
  continent <- data$Continent
  
  # Combine data into a data frame
  anova_data <- data.frame(LifeExpectancy = life_2010, Continent = continent)
  
  # Perform the ANOVA
  anova_result <- aov(LifeExpectancy ~ Continent, data = anova_data)
  
  # Display hypotheses
  cat("Null Hypothesis (H0): There is no significant difference in life expectancy across continents in 2010.\n")
  cat("Alternative Hypothesis (H1): There is a significant difference in life expectancy across continents in 2010.\n\n")
  
  # Display the ANOVA summary
  print(summary(anova_result))
  
  # Decision based on ANOVA
  p_value <- summary(anova_result)[[1]][["Pr(>F)"]][1]
  if (p_value < 0.05) {
    cat("\nResult: Reject the null hypothesis. Significant differences exist.\n")
    
    # Perform post-hoc tests (Tukey HSD)
    cat("\nPerforming post-hoc analysis (Tukey HSD):\n")
    posthoc_result <- TukeyHSD(anova_result)
    print(posthoc_result)
  } else {
    cat("\nResult: Fail to reject the null hypothesis. No significant differences exist.\n")
  }
}

# Call the function to perform the ANOVA test
performANOVA(lifeData)


