# 군집분석 — 단일연결 덴드로그램의 높이와 군집 수 절단
# 적용 범위: 연결한 R 공식문서의 함수·반환값 정의를 학습자료에 적용한 응용 예제입니다. 입력 자료의 성격은 위에 명시했으며, 표시 코드·콘솔 출력·R 그림은 사전 실행해 함께 생성했습니다.
# 출처: https://stat.ethz.ch/R-manual/R-patched/library/stats/html/hclust.html
# 출처: https://stat.ethz.ch/R-manual/R-patched/library/stats/html/cutree.html
# 실행 확인 환경: R version 4.6.2 (2026-10-29)
# 아래 코드를 실행하면 출력과 그림을 확인할 수 있습니다.

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

x <- matrix(c(0,1,4,9,16,25),ncol=1)
hc <- hclust(dist(x),method="single")
hc$height
by_height <- cutree(hc,h=6)
by_count <- cutree(hc,k=3)
cbind(높이6=by_height, 군집수3=by_count)
plot(hc,labels=x[,1],hang=-1,main="단일연결법: 높이 6에서 절단",
     xlab="관측값",ylab="병합 거리",sub="")
rect.hclust(hc,k=3,border=c("#2563EB","#15803D","#7C3AED"))
abline(h=6,col="#DC2626",lty=2)
