# 가설검정과 유의성 판단 — 같은 10명을 두 번 측정한 대응표본 t 검정
# 적용 범위: t.test 공식문서의 sleep 자료 재구성과 paired=TRUE 예제를 사용합니다. 그래프와 대상자 수·평균 차이 출력은 학습을 위해 추가했습니다. 차이의 방향은 약 1−약 2입니다.
# 출처: https://stat.ethz.ch/R-manual/R-patched/library/stats/html/t.test.html
# 출처: https://stat.ethz.ch/R-manual/R-patched/library/datasets/html/sleep.html
# 실행 확인 환경: R version 4.6.2 (2026-10-29)
# 아래 코드를 실행하면 출력과 그림을 확인할 수 있습니다.

# 재현 설정: 같은 난수 방식과 출력 자릿수를 사용합니다.
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
set.seed(2026)
options(width = 90, digits = 7, scipen = 7)

sleep2 <- reshape(sleep, direction = "wide", idvar = "ID", timevar = "group")
sleep2 <- sleep2[order(sleep2$ID), ]
result <- t.test(sleep2$extra.1, sleep2$extra.2, paired = TRUE)
result
difference <- sleep2$extra.1 - sleep2$extra.2
c(대상자수 = nrow(sleep2), 평균차이 = mean(difference))
values <- as.matrix(sleep2[, c("extra.1", "extra.2")])
matplot(1:2, t(values), type = "b", pch = 16, lty = 1,
        col = "#94A3B8", xaxt = "n", xlab = "같은 대상자에게 적용한 약",
        ylab = "수면 증가시간(시간)", main = "ID를 맞춘 대응 비교")
axis(1, at = 1:2, labels = c("약 1", "약 2"))
lines(1:2, colMeans(values), type = "b", col = "#2563EB", lwd = 3, pch = 19)
legend("topleft", c("대상자별 두 측정", "평균"), col = c("#94A3B8", "#2563EB"),
       lty = 1, pch = 16, bty = "n")
