# ==============================================================================
# RAO STATISTICS — PARAMETRIC HYPOTHESIS TESTING REPRODUCIBLE SCRIPT
# Analysis: Independent Two-Sample Student's t-Test & Pooled Variance Confidence Interval
# Author: Rao Statistics Academic Laboratories
# Website: https://rao-statistics.vercel.app
# ==============================================================================

# 1. Load Required Libraries
if (!requireNamespace("car", quietly = TRUE)) install.packages("car")
library(car)

# 2. Data Ingestion
data_file <- "two_sample_ttest_exam_cohorts.csv"
if (file.exists(data_file)) {
  df <- read.csv(data_file)
} else {
  # Fallback benchmark cohort data
  set.seed(42)
  df <- data.frame(
    student_id = 1:24,
    cohort = rep(c("Cohort A", "Cohort B"), each = 12),
    exam_score = c(84.5, 79.0, 88.0, 82.5, 91.0, 76.5, 85.0, 89.5, 81.0, 87.5, 93.0, 83.5,
                   72.0, 68.5, 77.0, 74.0, 81.5, 69.0, 75.5, 78.0, 71.5, 76.0, 80.0, 73.5)
  )
}

# 3. Descriptive Summaries by Cohort
cat("--- DESCRIPTIVE STATISTICS ---\n")
tapply(df$exam_score, df$cohort, function(x) {
  c(n = length(x), mean = mean(x), sd = sd(x), se = sd(x)/sqrt(length(x)))
})

# 4. Assumption Verification
cat("\n--- ASSUMPTION 1: NORMALITY (Shapiro-Wilk) ---\n")
by(df$exam_score, df$cohort, shapiro.test)

cat("\n--- ASSUMPTION 2: HOMOGENEITY OF VARIANCE (Levene Test) ---\n")
leveneTest(exam_score ~ cohort, data = df)

# 5. Independent Two-Sample Pooled t-Test
cat("\n--- INDEPENDENT TWO-SAMPLE t-TEST ---\n")
ttest_res <- t.test(exam_score ~ cohort, data = df, var.equal = TRUE, conf.level = 0.95)
print(ttest_res)

# 6. Effect Size: Cohen's d
pooled_sd <- sqrt(
  ((12 - 1)*sd(df$exam_score[df$cohort == "Cohort A"])^2 +
   (12 - 1)*sd(df$exam_score[df$cohort == "Cohort B"])^2) / (12 + 12 - 2)
)
cohens_d <- (mean(df$exam_score[df$cohort == "Cohort A"]) - mean(df$exam_score[df$cohort == "Cohort B"])) / pooled_sd
cat("\nPooled Standard Deviation (s_p):", round(pooled_sd, 4))
cat("\nCohen's d Effect Size:", round(cohens_d, 4), "\n")
