install.packages("gapminder", repos = "https://cloud.r-project.org")

library(gapminder)

# Ensure dataset is loaded
data("gapminder")

# Extract life expectancy data
life_data <- gapminder$lifeExp

# Generate 1000 sample means (n = 30)
sample_means <- replicate(1000,
                          mean(sample(life_data, size = 30, replace = TRUE)))

# Try with n = 10 and n = 100
means_10 <- replicate(1000,
                      mean(sample(life_data, size = 10, replace = TRUE)))

means_100 <- replicate(1000,
                       mean(sample(life_data, size = 100, replace = TRUE)))

# Visualise
par(mfrow = c(1,3))

hist(means_10, main = "n = 10", xlab = "Sample Mean", col = "lightblue")
hist(sample_means, main = "n = 30", xlab = "Sample Mean", col = "lightgreen")
hist(means_100, main = "n = 100", xlab = "Sample Mean", col = "lightpink")
par(mfrow = c(1,1))
simulate_means <- function(n, reps = 1000) {
  replicate(reps, mean(sample(life_data, size = n, replace = TRUE)))
}

sample_sizes <- c(10, 30, 50, 100)
par(mfrow = c(2,2))
for (n in sample_sizes) {
  hist(simulate_means(n), main = paste("sample mean distribution(n=",n,")"))}