# 데이터마트와 데이터 전처리 — 실제 결측 자료에서 평균 대치가 산포를 줄이는 과정
# 적용 범위: 공식 airquality의 Ozone 자료에 base R의 mean()·var()를 적용한 학습용 비교입니다. airquality 문서의 산점도 예제를 그대로 옮긴 것은 아닙니다. mice 공식 패키지 설명서의 평균 대치 한계와 연결하되 mice 함수를 실행하지 않았으며, 이 자료의 결측 메커니즘을 MCAR로 가정하거나 판정하지 않습니다.
# 출처: https://stat.ethz.ch/R-manual/R-patched/library/datasets/html/airquality.html
# 출처: https://stat.ethz.ch/R-manual/R-patched/library/base/html/mean.html
# 출처: https://stat.ethz.ch/R-manual/R-patched/library/stats/html/cor.html
# 출처: https://cran.r-project.org/web/packages/mice/mice.pdf#page=107
# 실행 확인 환경: R version 4.6.2 (2026-10-29)
# 아래 코드를 실행하면 출력과 그림을 확인할 수 있습니다.

x <- airquality$Ozone
observed <- x[!is.na(x)]
filled <- x
filled[is.na(filled)] <- mean(observed)
summary_table <- data.frame(자료 = c("관측값만", "평균 대치 후"),
  관측수 = c(length(observed), length(filled)),
  평균 = c(mean(observed), mean(filled)),
  표본분산 = c(var(observed), var(filled)))
cat("전체 행·관측값·결측값 수:\n")
print(c(전체 = length(x), 관측 = length(observed), 결측 = sum(is.na(x))))
print(summary_table)
cat("대치 후 분산 / 관측값 분산:\n")
print(var(filled) / var(observed))
breaks <- seq(0, 180, by = 20)
h_observed <- hist(observed, breaks = breaks, plot = FALSE)
h_filled <- hist(filled, breaks = breaks, plot = FALSE)
top <- max(h_observed$density, h_filled$density) * 1.15
par(mfrow = c(1, 2), mar = c(4.5, 6, 3.5, 1))
plot(h_observed, freq = FALSE, ylim = c(0, top), col = "#93C5FD",
  main = "관측된 Ozone 116개", xlab = "Ozone (ppb)", ylab = "")
mtext("확률밀도", side = 2, line = 4.3, las = 0)
abline(v = mean(observed), col = "#D97706", lwd = 2)
plot(h_filled, freq = FALSE, ylim = c(0, top), col = "#93C5FD",
  main = "평균으로 37개 대치: 총 153개", xlab = "Ozone (ppb)", ylab = "")
mtext("확률밀도", side = 2, line = 4.3, las = 0)
abline(v = mean(filled), col = "#D97706", lwd = 2)
