# Install necessary libraries (run once)
install.packages(c("gapminder", "dplyr", "ggplot2", "ggpubr"))

# Load libraries
library(gapminder)
library(dplyr)
library(ggplot2)
library(ggpubr)

#🧠 1. Sampling Distribution and Central Limit Theorem (CLT)
# Extract life expectancy data
life_data <- gapminder$lifeExp

# Generate 1000 sample means (sample size = 30)
sample_means <- replicate(1000, mean(sample(life_data, size = 30, replace = TRUE)))

# Visualize sampling distribution
hist(sample_means, main = "Sampling Distribution of Sample Mean", xlab = "Mean Life Expectancy")

# Effect of sample size
means_10  <- replicate(1000, mean(sample(life_data, 10, replace = TRUE)))
means_100 <- replicate(1000, mean(sample(life_data, 100, replace = TRUE)))

# Compare histograms
par(mfrow = c(1, 2))
hist(means_10, main = "n = 10")
hist(means_100, main = "n = 100")

# Function to simulate multiple sample sizes
simulate_means <- function(n, reps = 1000) {
  replicate(reps, mean(sample(life_data, size = n, replace = TRUE)))
}


#2. Correlation Analysis
# Plot several sample sizes
sample_sizes <- c(10, 30, 50, 100)
par(mfrow = c(2, 2))
for (n in sample_sizes) {
  hist(simulate_means(n), main = paste("n =", n))
}

# Pearson correlation (linear relationship)
cor(gapminder$lifeExp, gapminder$gdpPercap, method = "pearson")

# Spearman correlation (non-linear/monotonic)
cor(gapminder$lifeExp, gapminder$gdpPercap, method = "spearman")

# Visualize correlation
ggscatter(gapminder, x = "gdpPercap", y = "lifeExp", add = "reg.line", conf.int = TRUE) +
  stat_cor(method = "pearson", label.x = 3, label.y = 30)


#3. t-Test – Comparing Two Groups (Europe vs Africa)
europe <- gapminder %>% filter(continent == "Europe") %>% pull(lifeExp)
africa <- gapminder %>% filter(continent == "Africa") %>% pull(lifeExp)

# Two-sample t-test
t_result <- t.test(europe, africa)
t_result


#4. Simple Linear Regression
model <- lm(lifeExp ~ gdpPercap, data = gapminder)
summary(model)

# Visualize regression line
ggplot(gapminder, aes(x = gdpPercap, y = lifeExp)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE, color = "blue") +
  labs(title = "Simple Linear Regression: GDP vs Life Expectancy")


#5. Multiple Linear Regression
model_multi <- lm(lifeExp ~ gdpPercap + year + continent, data = gapminder)
summary(model_multi)



