# 회귀분석 — 회귀 진단 그림 네 장을 같은 모형에서 읽기
# 적용 범위: plot.lm 공식문서가 제공하는 진단 그림을 cars 모형에 적용하고 한국어 축·설명을 추가했습니다. 라벨은 자동으로 선택된 관측 번호이며 자동 삭제 기준이 아닙니다.
# 출처: https://stat.ethz.ch/R-manual/R-patched/library/stats/html/plot.lm.html
# 출처: https://stat.ethz.ch/R-manual/R-patched/library/datasets/html/cars.html
# 실행 확인 환경: R version 4.6.2 (2026-10-29)
# 아래 코드를 실행하면 출력과 그림을 확인할 수 있습니다.

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

fit <- lm(dist ~ speed, data = cars)
important <- order(cooks.distance(fit), decreasing = TRUE)[1:3]
round(data.frame(관측번호 = important, 잔차 = residuals(fit)[important],
                 표준화잔차 = rstandard(fit)[important],
                 레버리지 = hatvalues(fit)[important],
                 Cook거리 = cooks.distance(fit)[important]), 4)
par(mfrow = c(2, 2), mar = c(4.2, 4.8, 3, 3), cex = 0.85)
plot(fit, which = 1, ask = FALSE, caption = rep("", 6), ann = FALSE)
title(main = "잔차와 적합값", xlab = "적합 정지거리(ft)", ylab = "잔차(ft)")
plot(fit, which = 2, ask = FALSE, caption = rep("", 6), ann = FALSE)
title(main = "정규 Q-Q", xlab = "정규 이론 분위수", ylab = "표준화 잔차")
plot(fit, which = 3, ask = FALSE, caption = rep("", 6), ann = FALSE)
title(main = "산포와 적합값", xlab = "적합 정지거리(ft)", ylab = "표준화 잔차 절댓값의 제곱근")
plot(fit, which = 5, ask = FALSE, caption = rep("", 6), ann = FALSE)
title(main = "잔차와 레버리지", xlab = "레버리지", ylab = "표준화 잔차")
