# 2群の平均差の比較：対応のない t 検定 × 箱ひげ図
# sample-data の親フォルダを作業ディレクトリにして実行します。
# 初回だけ必要に応じて実行: install.packages(c("ggplot2", "tidyverse"))

set.seed(20261028)  # 再実行時の乱数を固定
library(tidyverse)

dat <- read.csv("sample-data/sample_independent_t_scores.csv")
# 差の方向を「介入群 − 対照群」に揃える
dat$group <- factor(dat$group, levels = c("Intervention", "Control"))

# 群ごとの要約統計
dat %>%
  group_by(group) %>%
  summarise(
    n = n(),
    mean = mean(score),
    sd = sd(score),
    median = median(score)
  )

# Student の t 検定（等分散を仮定）
tt_student <- t.test(score ~ group, data = dat, var.equal = TRUE)
tt_student

# Welch の t 検定（等分散を仮定しない）
tt_welch <- t.test(score ~ group, data = dat, var.equal = FALSE)
tt_welch

# 効果量の例（手計算）
group_summary <- dat %>%
  group_by(group) %>%
  summarise(
    n = n(),
    mean = mean(score),
    sd = sd(score)
  )

spooled <- sqrt(((group_summary$sd[1]^2 * (group_summary$n[1] - 1)) +
                 (group_summary$sd[2]^2 * (group_summary$n[2] - 1))) /
                (sum(group_summary$n) - 2))

cohens_d <- (group_summary$mean[1] - group_summary$mean[2]) / spooled
cohens_d

library(ggplot2)

ggplot(dat, aes(x = group, y = score, fill = group)) +
  geom_boxplot(width = 0.62, alpha = 0.7, outlier.shape = 21) +
  stat_summary(fun = mean, geom = "point", size = 3, color = "black") +
  labs(
    x = NULL,
    y = "Test score",
    title = "Distribution of test scores by group"
  ) +
  theme_minimal(base_size = 13) +
  theme(legend.position = "none")
