# 통계의 기초 — 척도와 기술통계 — KS 통계량 — 두 집단 누적분포의 최대 차이
# 적용 범위: 연결된 원문은 함수·수식의 정의를 뒷받침하며, 이 코드는 고정 학습자료에 적용한 응용 예제입니다. 콘솔 출력과 R 저장 그림은 표시된 코드를 사전 실행해 생성했습니다.
# 출처: https://stat.ethz.ch/R-manual/R-patched/library/stats/html/ks.test.html
# 출처: https://stat.ethz.ch/R-manual/R-patched/library/stats/html/ecdf.html
# 실행 확인 환경: R version 4.6.2 (2026-10-29)
# 아래 코드를 실행하면 출력과 그림을 확인할 수 있습니다.

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

good <- c(520, 560, 590, 610, 630, 650, 670, 700, 740, 800)  # 정상 고객 신용점수
bad  <- c(300, 350, 400, 420, 450, 480, 500, 540, 580, 620)  # 부실 고객 신용점수
ks.test(bad, good)$statistic          # 두 ECDF의 최대 수직 거리 D
x <- sort(unique(c(good, bad)))
x[which.max(abs(ecdf(bad)(x) - ecdf(good)(x)))]   # 차이가 최대인 점수
plot(ecdf(bad), col = "#DC2626", xlim = range(c(good, bad)), ylim = c(0, 1),
     verticals = TRUE, do.points = FALSE, main = "두 집단 경험누적분포의 최대 차이",
     xlab = "신용점수(가상자료)", ylab = "누적 비율")
plot(ecdf(good), col = "#2563EB", add = TRUE, verticals = TRUE, do.points = FALSE)
max_point <- x[which.max(abs(ecdf(bad)(x) - ecdf(good)(x)))]
segments(max_point, ecdf(good)(max_point), max_point, ecdf(bad)(max_point),
         col = "#15803D", lwd = 3)
text(max_point + 20, 0.45, "D = 0.7", adj = 0, col = "#15803D")
legend("topleft", c("부실 고객", "정상 고객"),
       col = c("#DC2626", "#2563EB"), lty = 1, bty = "n")
