#Student name:Lakkisetty Sai Vishnu Vardhan
#Student id: 2412185


# Question 1: Load and Preprocess the Dataset

# Load the dataset from a CSV file
lifeData <- read.csv("Life Expectancy.csv", header = TRUE)

# Convert "Continent" column to factor to treat it as a category
lifeData$Continent <- factor(lifeData$Continent)

# Convert "Hemisphere" column to factor to treat it as a category
lifeData$Hemisphere <- factor(lifeData$Hemisphere)

# Convert "Human.Development.Group" column to factor to treat it as a category
lifeData$Human.Development.Group <- factor(lifeData$Human.Development.Group)

# Print the dataset to ensure it loaded correctly
print(lifeData)


# Question 2.2: Calculate Mean Life Expectancy by Continent for Selected Years

# Select columns of years ending in 5 or 0 for analysis
yearsOfInterest <- c("Life.Expectancy.at.Birth..1995.", 
                     "Life.Expectancy.at.Birth..2000.", 
                     "Life.Expectancy.at.Birth..2005.", 
                     "Life.Expectancy.at.Birth..2010.", 
                     "Life.Expectancy.at.Birth..2015.", 
                     "Life.Expectancy.at.Birth..2020.")

# Select "Continent" column and chosen year columns for calculations
filteredData <- lifeData[, c("Continent", yearsOfInterest)]

# Calculate average life expectancy for each row, ignoring missing values
filteredData$MeanLifeExpectancy <- rowMeans(filteredData[, -1], na.rm = TRUE)

# Calculate average life expectancy for each continent
continentAverages <- tapply(filteredData$MeanLifeExpectancy, filteredData$Continent, mean, na.rm = TRUE)

# Create a data frame to store and display the results
resultData <- data.frame(Continent = names(continentAverages), MeanLifeExpectancy = continentAverages)

# Print the calculated results
print(resultData)


# Question 3: Correlation Between HDI Rank and Life Expectancy (2021)

# Extract HDI Rank and Life Expectancy data for 2021
hdiRank <- lifeData$HDI.Rank..2021.
lifeExpectancy2021 <- lifeData$Life.Expectancy.at.Birth..2021.

# Find rows where both columns have valid (non-missing) data
validIndices <- !is.na(hdiRank) & !is.na(lifeExpectancy2021)

# Calculate the correlation between HDI Rank and Life Expectancy
correlationValue <- cor(hdiRank[validIndices], lifeExpectancy2021[validIndices])

# Print the correlation value
print(correlationValue)


# Question 4: Display Life Expectancy Trends for a Country

# Function to create a graph for life expectancy trends for a specific country
plotLifeExpectancy <- function(selectedCountry, fromYear, toYear) {
  # Filter data for the selected country
  countrySpecificData <- lifeData[lifeData$Country == selectedCountry, ]
  
  # Generate column names for the years provided
  columnsForYears <- paste0("Life.Expectancy.at.Birth..", fromYear:toYear, ".")
  
  # Extract the data for the selected years
  years <- fromYear:toYear
  lifeExpectancyValues <- as.numeric(countrySpecificData[, columnsForYears])
  
  # Plot the graph to show life expectancy trends
  plot(years, lifeExpectancyValues, type = "b", pch = 19, col = "red",
       xlab = "Year", ylab = "Life Expectancy",
       main = paste("Life Expectancy Trends in", selectedCountry))
}

# Example: Display life expectancy trends for Canada from 1995 to 2020
plotLifeExpectancy("Canada", 1995, 2020)


# Question 5: Compare Life Expectancies for Multiple Countries

# Function to compare life expectancy trends for multiple countries
compareLifeExpectancies <- function(startYear, endYear, countryList) {
  # Filter data for the selected countries
  countryData <- lifeData[lifeData$Country %in% countryList, ]
  
  # Generate column names for the years provided
  yearsToAnalyze <- paste0("Life.Expectancy.at.Birth..", startYear:endYear, ".")
  
  # Extract data for the first country
  years <- startYear:endYear
  firstCountry <- as.numeric(countryData[1, yearsToAnalyze])
  
  # Plot the data for the first country
  plot(years, firstCountry, type = "l", lwd = 2, col = 1,
       xlab = "Year", ylab = "Life Expectancy",
       main = "Life Expectancy Comparison Across Countries")
  
  # Add lines for the remaining countries
  for (i in 2:nrow(countryData)) {
    countryLifeExpectancy <- as.numeric(countryData[i, yearsToAnalyze])
    lines(years, countryLifeExpectancy, col = i, lwd = 2)
  }
  
  # Add a legend for the countries
  legend("topright", legend = countryList, col = 1:length(countryList), lty = 1, lwd = 2)
}

# Example: Compare life expectancy trends for six countries from 2000 to 2020
compareLifeExpectancies(2000, 2020, c("Australia", "India", "Japan", "Brazil", "USA", "Canada"))


# Question 7: Perform t-test for Life Expectancy (1990 vs 2020)

# Extract data for life expectancy in 1990
life1990 <- as.numeric(lifeData$Life.Expectancy.at.Birth..1990.)

# Extract data for life expectancy in 2020
life2020 <- as.numeric(lifeData$Life.Expectancy.at.Birth..2020.)

# Perform a t-test to compare life expectancy in 1990 and 2020
tTestResult <- t.test(life1990, life2020)

# Print the t-test results
print(tTestResult)

# Check if the p-value is significant and interpret the results
if (tTestResult$p.value < 0.05) {
  cat("Reject the null hypothesis: Significant difference in life expectancy between 1990 and 2020.\n")
} else {
  cat("Fail to reject the null hypothesis: No significant difference in life expectancy between 1990 and 2020.\n")
}


# Question 8: Perform ANOVA Test for Life Expectancies by Continent in 2010

# Extract data for life expectancy in 2010
life2010 <- as.numeric(lifeData$Life.Expectancy.at.Birth..2010.)

# Extract data for continents
continent <- lifeData$Continent

# Create a dataset for the ANOVA test
anovaData <- data.frame(Continent = continent, LifeExpectancy = life2010)

# Perform an ANOVA test to compare life expectancy across continents
anovaResult <- aov(LifeExpectancy ~ Continent, data = anovaData)

# Print the ANOVA summary
print(summary(anovaResult))
