# Load required libraries
library(readr)
library(dplyr)
library(ggplot2)
library(tidyr)
library(stats)
library(car)

# 1. Load and prepare the data
lifeData <- read.csv("~/Desktop/Life Expectancy.csv")

# Convert appropriate 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 data frame
print("First few rows of the data:")
print(head(lifeData))

# 2. Create continentData for years divisible by 5
# Get all year columns (fixing the pattern matching)
all_cols <- names(lifeData)
year_cols <- all_cols[grep("^Life.Expectancy.at.Birth", all_cols)]
years <- as.numeric(sub(".*\\.(\\d{4})\\.", "\\1", year_cols))
year_cols_div5 <- year_cols[years %% 5 == 0]

# Calculate mean life expectancy by continent for these years
continentData <- lifeData %>%
  group_by(Continent) %>%
  summarise(across(all_of(year_cols_div5), mean))

print("\nContinent Data for years divisible by 5:")
print(continentData)


# 3. HDI Rank Correlation Function
HDIRankCorrelation <- function() {
  correlation <- cor(lifeData$HDI.Rank..2021.,
                     lifeData[, grep("2021", names(lifeData))],
                     use = "complete.obs")
  return(correlation)
}

print("\nHDI Rank Correlation with Life Expectancy 2021:")
print(HDIRankCorrelation())

# 4. Display Graph Function
displayGraph <- function(country_name, start_year, end_year) {
  # Get data for specific country
  country_data <- lifeData[lifeData$Country == country_name, ]
  
  # Get relevant year columns
  all_cols <- names(lifeData)
  year_cols <- all_cols[grep("^Life.Expectancy.at.Birth", all_cols)]
  years <- as.numeric(sub(".*\\.(\\d{4})\\.", "\\1", year_cols))
  selected_cols <- year_cols[years >= start_year & years <= end_year]
  
  # Reshape data for plotting
  plot_data <- country_data %>%
    select(Country, all_of(selected_cols)) %>%
    pivot_longer(cols = !Country,
                 names_to = "Year",
                 values_to = "Life_Expectancy") %>%
    mutate(Year = as.numeric(sub(".*\\.(\\d{4})\\.", "\\1", Year)))
  
  # Create plot
  ggplot(plot_data, aes(x = Year, y = Life_Expectancy)) +
    geom_line() +
    geom_point() +
    labs(title = paste("Life Expectancy in", country_name),
         x = "Year",
         y = "Life Expectancy (years)") +
    theme_minimal()
}

print("\nDisplaying graph for Australia (1995-2020):")
australia_plot <- displayGraph("Australia", 1995, 2020)
print(australia_plot)

# 5. Compare Countries Function
compareCountries <- function(start_year, end_year, countries) {
  # Filter data for selected countries
  selected_data <- lifeData[lifeData$Country %in% countries, ]
  
  # Get relevant year columns
  all_cols <- names(lifeData)
  year_cols <- all_cols[grep("^Life.Expectancy.at.Birth", all_cols)]
  years <- as.numeric(sub(".*\\.(\\d{4})\\.", "\\1", year_cols))
  selected_cols <- year_cols[years >= start_year & years <= end_year]
  
  # Reshape data for plotting
  plot_data <- selected_data %>%
    select(Country, all_of(selected_cols)) %>%
    pivot_longer(cols = !Country,
                 names_to = "Year",
                 values_to = "Life_Expectancy") %>%
    mutate(Year = as.numeric(sub(".*\\.(\\d{4})\\.", "\\1", Year)))
  
  # Create plot
  ggplot(plot_data, aes(x = Year, y = Life_Expectancy, color = Country)) +
    geom_line() +
    geom_point() +
    labs(title = "Life Expectancy Comparison",
         x = "Year",
         y = "Life Expectancy (years)") +
    theme_minimal()
}

print("\nComparing life expectancy for selected countries (2000-2020):")
example_countries <- c("Australia", "Japan", "Brazil", "Kenya", "India", "Canada")
comparison_plot <- compareCountries(2000, 2020, example_countries)
print(comparison_plot)


# 6. HDI Rank Correlation Function
HDIRankCorrelation <- function() {
  correlation <- cor(lifeData$HDI.Rank..2021.,
                     lifeData[, grep("2021", names(lifeData))],
                     use = "complete.obs")
  return(correlation)
}

print("\nHDI Rank Correlation with Life Expectancy 2021:")
print(HDIRankCorrelation())





# 7. T-test Analysis
print("\nPerforming t-test between 1990 and 2020 life expectancy:")
t_test_result <- t.test(lifeData$`Life.Expectancy.at.Birth..1990.`,
                        lifeData$`Life.Expectancy.at.Birth..2020.`,
                        paired = TRUE)
print(t_test_result)


# 8. ANOVA and Post-hoc Analysis
print("\nPerforming ANOVA test for continental differences in 2010:")
anova_result <- aov(Life.Expectancy.at.Birth..2010. ~ Continent, data = lifeData)
print(summary(anova_result))

print("\nPerforming Tukey's HSD test for pairwise comparisons:")
tukey_result <- TukeyHSD(anova_result)
print(tukey_result)

# Create boxplot visualization
print("\nCreating boxplot of life expectancy by continent:")
boxplot(Life.Expectancy.at.Birth..2010. ~ Continent, data = lifeData,
        main = "Life Expectancy by Continent in 2010",
        xlab = "Continent",
        ylab = "Life Expectancy (years)")

# Add interpretations
cat("\nInterpretations:\n")
cat("1. T-test results: ", ifelse(t_test_result$p.value < 0.05, 
                                  "Reject null hypothesis - significant difference found between 1990 and 2020", 
                                  "Fail to reject null hypothesis"), "\n")

cat("2. ANOVA results: ", ifelse(summary(anova_result)[[1]]$"Pr(>F)"[1] < 0.05,
                                 "Reject null hypothesis - significant differences found between continents",
                                 "Fail to reject null hypothesis"), "\n")

# Display average improvement in life expectancy
mean_diff <- mean(lifeData$Life.Expectancy.at.Birth..2020. - 
                    lifeData$Life.Expectancy.at.Birth..1990., na.rm = TRUE)
cat(sprintf("\nAverage improvement in life expectancy (1990-2020): %.2f years\n", mean_diff))



