#Question 1

# Load the Excel file into a data frame

lifeData <- read.csv("Life Expectancy.csv",header= TRUE)       # Load data from CSV file with column headers

# Convert specified columns to factors for categorical analysis
lifeData$Continent <- factor(lifeData$Continent)               # Convert "Continent" column to a factor for grouping
lifeData$Hemisphere <- factor(lifeData$Hemisphere)             # Convert "Hemisphere" column to a factor
lifeData$Human.Development.Group <- factor(lifeData$Human.Development.Group) # Convert "Human Development Group" column to a factor


# Display the first few rows of the data frame for verification
head(lifeData)  


#Question 2

# Select columns for years divisible by 5
yearCols <- 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.")                 # Specify columns of interest for selected years

# Filter data for selected columns
filteredData <- lifeData[, c("Continent", yearCols)]             # Subset the data frame to focus on relevant columns

# Calculate mean for rows and then group by continent
filteredData$MeanLife <- rowMeans(filteredData[, -1], na.rm = TRUE)    # Exclude "Continent" column for row-wise means
continentMeans <- tapply(filteredData$MeanLife, filteredData$Continent, mean, na.rm = TRUE)   # Group means by continent

# Display results
data.frame(Continent = names(continentMeans), MeanLifeExpectancy = continentMeans)            # Show mean life expectancy by continent

#Question 3

# Extract columns for HDI rank and life expectancy in 2021
hdiRank <- lifeData$HDI.Rank..2021.
lifeExpectancy2021 <- lifeData$Life.Expectancy.at.Birth..2021.   # Life expectancy at birth for 2021

# Remove NA values
validData <- !is.na(hdiRank) & !is.na(lifeExpectancy2021)        # Identify rows with valid data (non-NA values)
cor(hdiRank[validData], lifeExpectancy2021[validData])           # Compute correlation coefficient between the two variables 

#Question 4

# Define a function to display life expectancy trends for a specific country
displayGraph <- function(country, startYear, endYear) {
  data <- lifeData[lifeData$Country == country, ]                # Filter data for the specified country
  yearCols <- paste0("Life.Expectancy.at.Birth..", startYear:endYear, ".")                    # Generate column names for years in range
  years <- startYear:endYear                                     # Sequence of years
  values <- as.numeric(data[, yearCols])                         # Extract life expectancy values as numeric for plotting
  plot(years, values, type = "l", col = "blue",                  # Line plot for life expectancy trends
       xlab = "Year", ylab = "Life Expectancy",                  # Label axes
       main = paste("Trend for", country))                       # Set the graph title dynamically
}

displayGraph("Australia", 1995, 2020)                            # Display Australia's life expectancy trends from 1995 to 2020


#Question 5

# Define a function to compare life expectancy trends across multiple countries
compareCountries <- function(countries, startYear, endYear) {
  data <- lifeData[lifeData$Country %in% countries, ]             # Filter data for selected countries
  years <- startYear:endYear                                      # Sequence of years for analysis
  for (i in 1:nrow(data)) {                                       # Loop through each country in the filtered data
    yearCols <- paste0("Life.Expectancy.at.Birth..", years, ".")  # Generate column names for years
    values <- as.numeric(data[i, yearCols])                       # Extract life expectancy values for the country
    if (i == 1) {
      plot(years, values, type = "l", col = i, xlab = "Year", ylab = "Life Expectancy",
           main = "Life Expectancy Trends")                       # Plot the first country's trend
    } else {
      lines(years, values, col = i)                               # Add additional countries' trends to the plot
    }
  }
}
# Example usage: Compare life expectancy trends for India, USA, and Canada
compareCountries(c("India", "USA", "Canada"), 1995, 2020)

#Question 6

# Define a function to calculate correlation between HDI rank and life expectancy
HDIRankcorrelation <- function(data) {
  # Extract relevant columns
  hdiRank <- data$HDI.Rank..2021.                                  # HDI rank for 2021
  lifeExpectancy2021 <- data$Life.Expectancy.at.Birth..2021.       # Life expectancy for 2021
  
  # Filter out rows with missing values
  validData <- !is.na(hdiRank) & !is.na(lifeExpectancy2021)        # Keep rows with valid data
  
  # Calculate and return the correlation
  correlation <- cor(hdiRank[validData], lifeExpectancy2021[validData]) # Correlation between HDI and life expectancy
  
  # Return the result
  return(correlation)                                              # Return the computed correlation
}

# Example usage: Compute and display correlation
HDIRankcorrelation(lifeData)

#Question 7

# Perform a t-test to compare life expectancy in 1990 and 2020
life1990 <- as.numeric(lifeData$Life.Expectancy.at.Birth..1990.)   # Life expectancy for 1990
life2020 <- as.numeric(lifeData$Life.Expectancy.at.Birth..2020.)   # Perform a paired t-test for the two time periods
tResult <- t.test(life1990, life2020)                              # Perform a paired t-test for the two time periods
print(tResult)                                                     # Display the results of the t-test

#Question 8

# Perform ANOVA to analyze differences in life expectancy across continents in 2010
life2010 <- as.numeric(lifeData$Life.Expectancy.at.Birth..2010.)   # Life expectancy for 2010
continent <- as.factor(lifeData$Continent)                         # Convert "Continent" to a factor for grouping
result <- aov(life2010 ~ continent)                                # Perform ANOVA to compare life expectancy by continent
summary(result)                                                    # Display the ANOVA results (F-statistic and p-value)


