#Student Name : PRATAHAMESH MAHESH ANDELI
#Student ID : 2408629
#-------------------------------------------------------------------------------
# Q.1 Solution: Load and Preprocess the Dataset
#-------------------------------------------------------------------------------

# Required Knowledge:
# - Data Frames and Subsetting (Chapter 4, Page 55-68)
# - Factors (Chapter 6, Page 121)

# Step 1: Load the dataset
lifeData <- read.csv("Life Expectancy.csv", header = TRUE)  # Load the CSV file with headers

# Step 2: Convert specific columns to factors
lifeData$Continent <- factor(lifeData$Continent)  # Convert Continent to a categorical variable
lifeData$Hemisphere <- factor(lifeData$Hemisphere)  # Convert Hemisphere to a categorical variable
lifeData$Human.Development.Group <- factor(lifeData$Human.Development.Group)  # Convert Human Development Group to a categorical variable

# Step 3: Display the resulting data frame
print(lifeData)  # Verify the dataset is loaded correctly

# Reference: The Art of R Programming by Norman Matloff (Chapters 4 and 6)
# Additional exploration of factors inspired by the examples in Chapter 6.

#-------------------------------------------------------------------------------
# Q.2 Solution: Calculate Mean Life Expectancy by Continent for Selected Years
#-------------------------------------------------------------------------------

# Part 1: Select Required Columns
continentCol <- "Continent"  # Specify the column representing continents

# Specify 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.")  # Columns with life expectancy data for specific years

# Verify selected columns
print(yearCols)  # Print column names to confirm selection

# Part 2: Filter and Prepare Data
filteredData <- lifeData[, c(continentCol, yearCols)]  # Select only the continent and required year columns
print(head(filteredData))  # Display the first few rows to confirm filtering

# Part 3: Calculate Row-Wise Means
filteredData$MeanLife <- rowMeans(filteredData[, yearCols], na.rm = TRUE)  # Compute mean life expectancy for each row
print(head(filteredData))  # Verify the updated dataset with mean values

# Part 4: Calculate Continent-Wise Mean
continentData <- tapply(filteredData$MeanLife, filteredData$Continent, mean, na.rm = TRUE)  # Group by continent and calculate the mean
continentData <- data.frame(Continent = names(continentData), MeanLifeExpectancy = as.numeric(continentData))  # Convert to a data frame
print(continentData)  # Display the final summary

# Reference: Matloff’s approach to summarizing data (Chapter 4) and additional exploration for `rowMeans`.

#-------------------------------------------------------------------------------
# Q.3 and Q.6: Calculate Correlation Between HDI Rank and Life Expectancy
#-------------------------------------------------------------------------------

HDIRankCorrelation <- function(data) {
  hdiRank <- data$HDI.Rank..2021.  # Extract HDI Rank column
  lifeExpectancy2021 <- data$Life.Expectancy.at.Birth..2021.  # Extract Life Expectancy for 2021
  
  validData <- !is.na(hdiRank) & !is.na(lifeExpectancy2021)  # Identify rows without missing values
  
  correlation <- cor(hdiRank[validData], lifeExpectancy2021[validData], use = "complete.obs")  # Compute the correlation
  return(correlation)  # Return the computed correlation
}

result <- HDIRankCorrelation(lifeData)  # Call the function with the dataset
print(result)  # Display the correlation result

# Reference: Hypothesis testing methods discussed in Matloff’s book (Chapter 10).

#-------------------------------------------------------------------------------
# Q.4: Display Graph for Life Expectancy Trends (1995–2020)
#-------------------------------------------------------------------------------

displayGraph <- function(countryName, startYear, endYear) {
  countryData <- lifeData[lifeData$Country == countryName, ]  # Filter rows for the selected country
  
  yearCols <- paste0("Life.Expectancy.at.Birth..", startYear:endYear, ".")  # Generate column names dynamically
  
  lifeExpectancy <- as.numeric(countryData[, yearCols])  # Extract life expectancy data for the specified years
  
  years <- seq(startYear, endYear, by = 1)  # Create a sequence of years
  
  plot(years, lifeExpectancy, type = "o", col = "blue", lwd = 2,  # Plot the graph
       xlab = "Year", ylab = "Life Expectancy",
       main = paste("Life Expectancy in", countryName, startYear, "to", endYear))
  
  grid(col = "gray")  # Add grid lines for better readability
}
displayGraph("Australia", 1995, 2020)  # Call the function for Australia

# Reference: Graphing techniques from Chapter 5.

#-------------------------------------------------------------------------------
# Q.5: Compare Life Expectancies for Multiple Countries
#-------------------------------------------------------------------------------

compareCountries <- function(startYear, endYear, countries) {
  countryData <- lifeData[lifeData$Country %in% countries, ]  # Filter rows for the selected countries
  
  yearCols <- paste0("Life.Expectancy.at.Birth..", startYear:endYear, ".")  # Generate column names dynamically
  
  selectedData <- countryData[, c("Country", yearCols)]  # Select relevant columns
  
  years <- seq(startYear, endYear, by = 1)  # Create a sequence of years
  
  lifeExpectancies <- lapply(1:nrow(selectedData), function(i) as.numeric(selectedData[i, -1]))  # Extract life expectancy data for each country
  
  plot(years, lifeExpectancies[[1]], type = "o", col = 1, lwd = 2,  # Plot the first country's data
       xlab = "Year", ylab = "Life Expectancy",
       main = "Life Expectancy Trends for Multiple Countries")
  
  for (i in 2:length(lifeExpectancies)) {
    lines(years, lifeExpectancies[[i]], type = "o", col = i, lwd = 2)  # Add lines for remaining countries
  }
  
  legend("bottomright", legend = countries, col = 1:length(countries), lwd = 2, pch = 1)  # Add legend
}

compareCountries(1995, 2020, c("Australia", "India", "USA", "Canada", "Japan", "Brazil"))  # Call the function

#-------------------------------------------------------------------------------
# Q.7: Perform t-test for Life Expectancy in 1990 and 2020
#-------------------------------------------------------------------------------

# Step 1: Extract data for 1990 and 2020
life1990 <- as.numeric(lifeData$Life.Expectancy.at.Birth..1990.)  # Extract life expectancy for 1990
life2020 <- as.numeric(lifeData$Life.Expectancy.at.Birth..2020.)  # Extract life expectancy for 2020

# Step 2: Display summary statistics for verification
print(summary(life1990))  # Print summary statistics for 1990 data
print(summary(life2020))  # Print summary statistics for 2020 data

# Step 3: Perform t-test
# H0 (Null Hypothesis): No significant difference in mean life expectancy between 1990 and 2020.
# H1 (Alternative Hypothesis): Significant difference in mean life expectancy between 1990 and 2020.

tTestResult <- t.test(life1990, life2020, var.equal = FALSE)  # Perform two-sample t-test with unequal variance

# Step 4: Display the test results
print(tTestResult)  # Print t-test result

# Step 5: Interpret the results
# If p-value < 0.05, reject H0. Otherwise, fail to reject H0.
if (tTestResult$p.value < 0.05) {
  cat("Conclusion: Reject H0. There is a significant difference in life expectancy between 1990 and 2020.\n")
} else {
  cat("Conclusion: Fail to reject H0. No significant difference in life expectancy between 1990 and 2020.\n")
}

# Reference: Matloff’s hypothesis testing methods (Chapter 10).

#-------------------------------------------------------------------------------
# Q.8: Perform ANOVA Test for Life Expectancy by Continent in 2010
#-------------------------------------------------------------------------------

# Step 1: Extract data for 2010 and group by continent
life2010 <- as.numeric(lifeData$Life.Expectancy.at.Birth..2010.)  # Extract life expectancy for 2010
continent <- as.factor(lifeData$Continent)  # Extract continent as a factor

# Combine into a data frame for ANOVA
anovaData <- data.frame(Continent = continent, LifeExpectancy = life2010)  # Create a data frame for analysis
print(head(anovaData))  # Display the first few rows for verification

# Step 2: Perform ANOVA test
# H0 (Null Hypothesis): No significant difference in mean life expectancy across continents.
# H1 (Alternative Hypothesis): At least one continent has a significantly different mean life expectancy.

anovaResult <- aov(LifeExpectancy ~ Continent, data = anovaData)  # Perform ANOVA test
summary(anovaResult)  # Display the summary of ANOVA results

# Step 3: Perform post-hoc test if significant difference is found
# Tukey's HSD Test helps identify specific groups with significant differences
tukeyResult <- TukeyHSD(anovaResult)  # Perform Tukey's Honest Significant Difference test
print(tukeyResult)  # Display Tukey's test results
plot(tukeyResult)  # Visualize the results of Tukey's HSD test

# Step 4: Interpretation of post-hoc results
# - Examine the confidence intervals in Tukey's HSD results.
# - If the confidence interval does not cross zero, the pair of groups has a significant difference.
# - This helps determine which continents have statistically different life expectancies.

# Example Conclusion:
# If ANOVA p-value < 0.05: Reject H0. Significant differences exist between continents.
# Tukey's HSD results highlight specific pairs (e.g., Asia vs Europe) with p-values < 0.05, confirming significant differences.

# Reference: Matloff’s book, Chapter 10, for ANOVA and post-hoc tests.
