준비 : 필요 패키지 설치 및 로드

# 클러스터링 분석에 필요한 패키지를 불러오는 단계입니다.
# - 계층적 클러스터링(hclust), K-means 등 다양한 분석 기법과
# - 결과 시각화를 위해 여러 패키지를 활용합니다.

# 만약 패키지가 설치되지 않았다면 아래 줄의 주석을 해제해서 한 번만 설치하면 됩니다.
# install.packages("cluster")     # 클러스터링 알고리즘 관련 함수 포함
# install.packages("factoextra")  # 클러스터링 결과 시각화 전용 패키지
# install.packages("ggdendro")    # 덴드로그램을 ggplot2로 표현할 수 있게 도와줌

# 1. cluster 패키지 로드
# - K-means, 계층적 클러스터링(hclust) 등에 필요한 함수들이 들어 있습니다.
library(cluster)

# 2. factoextra 패키지 로드
# - 클러스터링 결과를 시각화하거나 차원 축소 결과를 보기 좋게 표현할 수 있습니다.
# - 예: fviz_cluster(), fviz_dend() 등 시각화 전용 함수 제공
library(factoextra)
Loading required package: ggplot2
Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa
# 3. stats 패키지 로드
# - 평균, 표준편차, 거리 계산(dist), 계층적 군집(hclust) 등 기본 통계 분석 기능 제공
# - R의 base 패키지로 기본 탑재되어 있어 설치할 필요는 없습니다.
library(stats)

# 4. ggplot2 및 ggplot 기반 덴드로그램 시각화를 위한 ggplot2 + ggdenro
# - ggplot2: R에서 가장 널리 사용되는 시각화 패키지
# - ggdenro: 계층적 클러스터링의 덴드로그램을 ggplot2 스타일로 보여줄 수 있음
library(ggdendro)
library(ggplot2)

Q1: Load “wine” dataset and create the independent variable(x) set and dependent variable(y) set, respectively.

1-1) 와인 데이터셋 로딩 (CSV 파일 읽기)

# readr 패키지는 CSV 파일을 읽을 때 유용한 함수(read_csv)를 제공합니다.
# read_csv()는 read.csv()보다 더 빠르고 직관적인 출력 형식을 가짐
library(readr)

# [read_csv() 함수 설명]
# - 괄호 안에 파일 경로를 지정하면 해당 CSV 파일을 불러옵니다.
# - 경로는 절대 경로나 상대 경로 모두 사용 가능하며, Mac 기준으로는 ~/Documents/... 경로 사용

# "wine.csv" 파일을 불러와서 wine 변수에 저장합니다.
# 파일 경로는 Mac 기준으로 예시 경로이며, 개인 환경에 맞게 수정 가능합니다.
wine <- read_csv("~/Documents/R studio/wine.csv")
Rows: 178 Columns: 14
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr  (1): Class
dbl (13): Alcohol, Malic, Ash, Alcalinity, Magnesium, Phenols, Flavanoids, N...

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# View() 함수를 사용하면 데이터를 엑셀처럼 테이블 형태로 시각적으로 확인할 수 있습니다.
# 이 함수는 RStudio에서만 작동하며, 데이터 확인에 매우 유용합니다.
# View(wine)

1-2) 독립/종속 변수 분리

# 데이터프레임에서 첫 번째 열은 와인의 품종(Class)을 의미하므로 종속 변수로 설정하고,
# 나머지 열들은 와인의 특성(예: 알코올 도수, 산도 등)을 나타내므로 독립 변수로 설정합니다.

# [1] 독립 변수 집합 x 생성
# wine[, -1]은 첫 번째 열을 제외한 모든 열을 의미하며, 
# 이는 예측에 사용될 수치형 변수들로 구성됨
x <- wine[, -1]

# [2] 종속 변수 집합 y 생성
# wine[, 1]은 첫 번째 열, 즉 와인의 품종 정보를 나타내는 열을 추출한 것으로,
# 각 와인이 어떤 Class(1, 2, 3)에 속하는지를 나타냄
y <- wine[, 1]

# [3] 데이터 확인
# View() 함수로 전체 데이터를 테이블 형태로 시각적으로 확인
# View(wine)

# [4] 독립 변수 x의 앞부분(4개 행)만 출력해서 내용 확인
head(x, 4)
# A tibble: 4 × 13
  Alcohol Malic   Ash Alcalinity Magnesium Phenols Flavanoids Nonflavanoid
    <dbl> <dbl> <dbl>      <dbl>     <dbl>   <dbl>      <dbl>        <dbl>
1    14.2  1.71  2.43       15.6       127    2.8        3.06         0.28
2    13.2  1.78  2.14       11.2       100    2.65       2.76         0.26
3    13.2  2.36  2.67       18.6       101    2.8        3.24         0.3 
4    14.4  1.95  2.5        16.8       113    3.85       3.49         0.24
# ℹ 5 more variables: Proanthocyanins <dbl>, Intensity <dbl>, Hue <dbl>,
#   OD280 <dbl>, Proline <dbl>

Q2:Scale the independent variable set.

# [스케일링(정규화, Scaling)이란?]
# - 변수마다 측정 단위나 범위가 다를 경우, 거리 기반 분석에서 왜곡이 발생할 수 있습니다.
# - 예) 알코올 도수는 0~15, 색상 점수는 0~5로 범위가 다르면 클러스터링 정확도에 영향을 줍니다.
# - 따라서, 모든 변수의 기준을 같게 맞추는 '전처리 작업'이 필요합니다.

# [scale() 함수 설명]
# - 기본적으로 Z-score 정규화를 수행합니다.
# - 계산식: (각 값 - 평균) / 표준편차
# - 결과적으로 **모든 변수의 평균은 0, 표준편차는 1**이 됩니다.
# - 이는 K-평균, 계층적 클러스터링 같은 거리 기반 분석에서 매우 중요합니다.

# [1] 독립 변수(x)를 정규화하여 x_scaled에 저장
x_scaled <- scale(x)

# [2] 정규화된 데이터의 상위 2개 행 미리보기
head(x_scaled, 2)
       Alcohol      Malic        Ash Alcalinity  Magnesium   Phenols Flavanoids
[1,] 1.5143408 -0.5606682  0.2313998  -1.166303 1.90852151 0.8067217  1.0319081
[2,] 0.2455968 -0.4980086 -0.8256672  -2.483841 0.01809398 0.5670481  0.7315653
     Nonflavanoid Proanthocyanins  Intensity       Hue    OD280   Proline
[1,]   -0.6577078       1.2214385  0.2510088 0.3610679 1.842721 1.0101594
[2,]   -0.8184106      -0.5431887 -0.2924962 0.4048188 1.110317 0.9625263
# [3] 변수별 평균 확인 (정규화가 잘 되면 평균 ≈ 0)
apply(x_scaled, 2, mean)
        Alcohol           Malic             Ash      Alcalinity       Magnesium 
   7.840170e-15    2.806744e-16   -4.071649e-15   -1.072800e-16   -4.958580e-17 
        Phenols      Flavanoids    Nonflavanoid Proanthocyanins       Intensity 
  -2.557255e-17    8.382808e-16    1.347237e-16   -1.649118e-15   -2.494883e-18 
            Hue           OD280         Proline 
   2.195497e-15    1.933534e-15   -1.434558e-16 
# [4] 변수별 표준편차 확인 (정규화가 잘 되면 표준편차 ≈ 1)
apply(x_scaled, 2, sd)
        Alcohol           Malic             Ash      Alcalinity       Magnesium 
              1               1               1               1               1 
        Phenols      Flavanoids    Nonflavanoid Proanthocyanins       Intensity 
              1               1               1               1               1 
            Hue           OD280         Proline 
              1               1               1 

Q3: Using independent variable set conduct hierarchical clustering with different methods (“single”, “complete”, “average”). Plot each dendrogram.

*계층적 클러스터링(Hierarchical Clustering) 이란? - 데이터를 서로 유사한 그룹으로 계층적으로 묶어 나가는 클러스터링 기법입니다. - 유사한 데이터끼리 가까운 거리로 묶이고, 그 묶음을 다시 상위 클러스터로 병합하며 최종적으로 전체 데이터가 하나로 통합됩니다. - 주로 덴드로그램(Dendrogram) 을 통해 시각화되며, 데이터 간 계층적 구조를 파악할 수 있습니다.

3-1) Single Linkage 방식 - 특징: 두 클러스터 간의 가장 가까운 거리를 기준으로 병합 - 장점: 복잡한 형상의 데이터에도 유연함 - 단점: ‘사슬 효과(chain effect)’ 발생 가능 (연결만 되고, 실제 거리가 먼 데이터도 묶임)

# [1] 거리 계산 (표준화된 독립 변수 집합 x_scaled 사용)
single_distmatrix <- dist(x_scaled)

# [2] hclust()로 single linkage 방식 클러스터링 수행
hc_single <- hclust(single_distmatrix, method = "single")

# [3] 클러스터 병합 정보 확인
head(hc_single)
$merge
       [,1] [,2]
  [1,]  -10  -48
  [2,] -132 -134
  [3,]  -12  -13
  [4,]  -16  -54
  [5,]  -93 -108
  [6,]  -35  -38
  [7,]   -1  -21
  [8,]  -17  -18
  [9,] -165 -173
 [10,]  -57    7
 [11,]  -23  -30
 [12,]  -41   10
 [13,] -105 -117
 [14,]  -24  -25
 [15,]  -28  -39
 [16,] -141 -143
 [17,]  -36   14
 [18,] -163   16
 [19,]  -64  -99
 [20,]  -27  -58
 [21,]  -91    5
 [22,]    4   20
 [23,] -112 -126
 [24,] -164 -171
 [25,]   -7   11
 [26,] -149 -175
 [27,]  -92   21
 [28,]  -83  -88
 [29,]  -55   12
 [30,]    8   22
 [31,] -140   18
 [32,] -157   26
 [33,]  -45    1
 [34,] -133    2
 [35,]  -11  -32
 [36,]  -89   27
 [37,] -107   13
 [38,]  -68   37
 [39,] -139 -166
 [40,]   29   33
 [41,]    9   32
 [42,] -146   24
 [43,]  -87   28
 [44,]    3   15
 [45,] -148 -161
 [46,]   -6  -19
 [47,] -168   41
 [48,] -156 -174
 [49,]  -52   44
 [50,]   25   40
 [51,]   49   50
 [52,] -172   47
 [53,]  -53   46
 [54,]   30   53
 [55,]  -81  -98
 [56,]   17   51
 [57,] -103   23
 [58,]  -37    6
 [59,]  -82   38
 [60,]  -90   43
 [61,] -162   31
 [62,]   45   52
 [63,]   56   58
 [64,] -127   57
 [65,] -167 -169
 [66,] -150 -152
 [67,] -115   64
 [68,]   34   42
 [69,]  -50   35
 [70,]  -43  -59
 [71,]   54   69
 [72,] -135 -136
 [73,]   -4   70
 [74,] -176   66
 [75,] -102   59
 [76,] -104   75
 [77,]  -49  -56
 [78,]   48   62
 [79,]   -9   63
 [80,]   71   79
 [81,]   73   80
 [82,]   65   78
 [83,] -159 -160
 [84,] -109   76
 [85,]   -8   81
 [86,]  -42  -44
 [87,]   36   60
 [88,]  -20  -40
 [89,]  -86   84
 [90,] -177   74
 [91,]  -85 -110
 [92,]   55   89
 [93,] -121   67
 [94,]  -29   85
 [95,]   77   94
 [96,] -151   90
 [97,]   -2   95
 [98,]   39   72
 [99,] -129   93
[100,]  -33   97
[101,]   -5  100
[102,] -155   98
[103,]   -3  101
[104,] -118   92
[105,]   99  104
[106,]  -34  103
[107,]   87  105
[108,] -144  102
[109,]   88  106
[110,] -114  107
[111,]  109  110
[112,]   82  108
[113,] -154  112
[114,]  -94  111
[115,]  -31  114
[116,] -142   68
[117,]   91  115
[118,] -101  117
[119,]  -22   86
[120,]   61  116
[121,]  -77  118
[122,]   96  113
[123,]  -65  121
[124,] -145  120
[125,]  -61  -69
[126,] -120  123
[127,]  -26  126
[128,] -178  122
[129,]  124  128
[130,]  -66  127
[131,]  -84  129
[132,]  -47  130
[133,] -153  131
[134,]  -95  132
[135,] -131  133
[136,]  -63  134
[137,]  119  136
[138,]   19  137
[139,]  -14  -15
[140,]  -46  138
[141,] -137 -138
[142,] -147  135
[143,]  -76  140
[144,]  -73  143
[145,]  -62  125
[146,] -106  144
[147,]  139  146
[148,]  142  145
[149,]  141  148
[150,] -170  149
[151,] -130  147
[152,]  -80 -123
[153,]  150  151
[154,] -158  153
[155,]  -75  154
[156,]  -67  155
[157,]  -78  156
[158,]  -71  157
[159,] -119  158
[160,]  -51  159
[161,] -113  160
[162,]  152  161
[163,]  -70  -79
[164,] -100  162
[165,]  -72  164
[166,] -124  165
[167,] -128  166
[168,] -116  167
[169,] -125  168
[170,]  -96  163
[171,]   83  169
[172,]  -97  171
[173,] -111  172
[174,]  -60  173
[175,] -122  174
[176,]  -74  175
[177,]  170  176

$height
  [1] 1.160843 1.188251 1.205954 1.222071 1.241887 1.264851 1.284271 1.288161
  [9] 1.296828 1.324025 1.331911 1.340696 1.348374 1.358855 1.361478 1.363560
 [17] 1.370611 1.378732 1.380142 1.382870 1.387890 1.418248 1.433903 1.440518
 [25] 1.447228 1.453793 1.457268 1.467187 1.467545 1.471205 1.482344 1.482473
 [33] 1.494457 1.508977 1.508987 1.520496 1.525974 1.545223 1.550962 1.556337
 [41] 1.556527 1.558535 1.567036 1.568580 1.574982 1.576543 1.578079 1.580445
 [49] 1.581156 1.582212 1.589026 1.592676 1.599000 1.600496 1.603496 1.606328
 [57] 1.615102 1.623307 1.634914 1.641285 1.650533 1.653828 1.671531 1.673727
 [65] 1.684904 1.693967 1.703682 1.707316 1.709144 1.709760 1.720964 1.730825
 [73] 1.733772 1.739964 1.742057 1.745761 1.752004 1.753828 1.756444 1.761992
 [81] 1.762220 1.763503 1.778945 1.782307 1.787060 1.790419 1.793249 1.814755
 [89] 1.819535 1.821081 1.825128 1.825172 1.826123 1.831551 1.839258 1.849210
 [97] 1.852135 1.852611 1.863070 1.909557 1.912972 1.920066 1.926862 1.938448
[105] 1.940164 1.950542 1.967276 1.969996 1.970307 1.971198 1.977704 1.986412
[113] 1.987607 2.006050 2.007469 2.008832 2.018574 2.044711 2.070141 2.078656
[121] 2.079317 2.082879 2.087748 2.088956 2.093797 2.095389 2.130095 2.137666
[129] 2.145495 2.148482 2.148840 2.154930 2.165547 2.182785 2.202890 2.203353
[137] 2.203755 2.208295 2.211630 2.211859 2.215128 2.217818 2.220080 2.265276
[145] 2.265291 2.285815 2.329241 2.356219 2.357356 2.393491 2.398171 2.413190
[153] 2.419783 2.433901 2.442622 2.459714 2.514725 2.521795 2.542696 2.594692
[161] 2.647854 2.732751 2.751642 2.767648 2.809071 2.821419 2.855266 2.927361
[169] 2.961673 2.970939 3.000725 3.302767 3.419517 3.630279 3.849549 3.896609
[177] 3.992191

$order
  [1]  96  70  79  74 122  60 111  97 159 160 125 116 128 124  72 100  80 123
 [19] 113  51 119  71  78  67  75 158 170 137 138 147 131 153  84 145 162 140
 [37] 163 141 143 142 133 132 134 146 164 171 178 151 177 176 150 152 154 167
 [55] 169 156 174 148 161 172 168 165 173 157 149 175 144 155 139 166 135 136
 [73]  62  61  69 130  14  15 106  73  76  46  64  99  22  42  44  63  95  47
 [91]  66  26 120  65  77 101  85 110  31  94  20  40  34   3   5  33   2  49
[109]  56  29   8   4  43  59  17  18  16  54  27  58  53   6  19  50  11  32
[127]   9  36  24  25  52  12  13  28  39   7  23  30  55  41  57   1  21  45
[145]  10  48  37  35  38 114  89  92  91  93 108  90  87  83  88 129 121 115
[163] 127 103 112 126 118  81  98  86 109 104 102  82  68 107 105 117

$labels
NULL

$method
[1] "single"

$call
hclust(d = single_distmatrix, method = "single")
# [4] 덴드로그램 시각화
plot(hc_single,
     main = "Single Linkage",  # 제목
     cex = 0.5)                # 숫자 크기 축소

# [5] 병합 기준선 추가
abline(h = 1.160843, col = "red", lwd = 2)   # 첫 병합 기준선
abline(h = 1.264851, col = "blue", lwd = 2)  # 여유있는 병합 기준선

# [6] 높이 값 텍스트로 명시 (왼쪽에 위치시킴)
text(x = 0, y = 1.160843, labels = "1.16", col = "red", pos = 4, cex = 0.9)
text(x = 0, y = 1.264851, labels = "1.26", col = "blue", pos = 4, cex = 0.9)

3-2) Complete Linkage 방식 - 특징: 두 클러스터 간의 가장 먼 거리를 기준으로 병합 - 장점: 클러스터 간 경계를 넓게 유지해 고르게 분포된 클러스터 형성 - 단점: 이상치나 노이즈에 민감할 수 있음

# [1] 거리 계산
complete_distmatrix <- dist(x_scaled)

# [2] 클러스터링 수행 (complete linkage 방식)
hc_complete <- hclust(complete_distmatrix, method = "complete")

# [3] 병합 정보 확인
head(hc_complete)
$merge
       [,1] [,2]
  [1,]  -10  -48
  [2,] -132 -134
  [3,]  -12  -13
  [4,]  -16  -54
  [5,]  -93 -108
  [6,]  -35  -38
  [7,]   -1  -21
  [8,]  -17  -18
  [9,] -165 -173
 [10,]  -23  -30
 [11,]  -41  -57
 [12,] -105 -117
 [13,]  -24  -25
 [14,]  -28  -39
 [15,] -141 -143
 [16,]  -64  -99
 [17,]  -27  -58
 [18,] -112 -126
 [19,] -164 -171
 [20,] -149 -175
 [21,]  -83  -88
 [22,]  -91  -92
 [23,] -140 -163
 [24,]  -11  -32
 [25,] -107   12
 [26,] -139 -166
 [27,] -148 -161
 [28,]   -6  -19
 [29,] -156 -174
 [30,] -168 -172
 [31,]  -81  -98
 [32,] -167 -169
 [33,] -150 -152
 [34,]  -43  -59
 [35,] -135 -136
 [36,]  -36   13
 [37,]   15   23
 [38,]  -49  -56
 [39,] -159 -160
 [40,] -104 -109
 [41,]  -42  -44
 [42,]  -89   22
 [43,] -103   18
 [44,]  -20  -40
 [45,]  -82  -86
 [46,] -176 -177
 [47,]   -7   10
 [48,]  -85 -110
 [49,]  -45  -55
 [50,]  -37    6
 [51,] -127 -129
 [52,]    7   11
 [53,]   -4  -53
 [54,]   -5  -29
 [55,]  -50   28
 [56,]    4    8
 [57,] -151   33
 [58,]    1   49
 [59,] -102   25
 [60,] -154 -157
 [61,] -133    2
 [62,]  -90 -115
 [63,] -162   37
 [64,]   -3   38
 [65,] -144   26
 [66,]  -52    3
 [67,] -142   19
 [68,]   17   50
 [69,]  -65  -87
 [70,]  -61  -69
 [71,]  -31   64
 [72,]  -68   59
 [73,]  -94  -95
 [74,]  -63  -77
 [75,]  -14  -15
 [76,] -137 -138
 [77,] -155   35
 [78,]   47   66
 [79,]   -2   14
 [80,]   24   55
 [81,]    9   20
 [82,]  -76 -101
 [83,]   43   51
 [84,]   -8  -46
 [85,]   -9  -47
 [86,]  -33  -66
 [87,]    5   42
 [88,] -120   40
 [89,]  -84   65
 [90,]   31   45
 [91,]  -80 -123
 [92,] -146   67
 [93,]  -34   56
 [94,]   34   53
 [95,]  -22   36
 [96,]  -62   70
 [97,] -121   48
 [98,] -178   32
 [99,] -114   62
[100,]  -73 -118
[101,]   27   30
[102,] -106   87
[103,]  -75   16
[104,]  -71  -78
[105,]   73   90
[106,]   21   99
[107,]   52   58
[108,]  -70  -79
[109,]   60   81
[110,] -131   61
[111,] -145   46
[112,]   29   76
[113,] -170   98
[114,]   74   82
[115,]   85  107
[116,] -124 -125
[117,]   68   95
[118,] -119   92
[119,]  -26   54
[120,]   63   89
[121,]   72  100
[122,] -130   91
[123,]  101  109
[124,] -153   57
[125,]  -51  -67
[126,]   86  117
[127,] -100 -116
[128,] -147  118
[129,]  -96  108
[130,] -113 -128
[131,]   41   79
[132,]   80   94
[133,]   83   88
[134,]   71   78
[135,]   44   84
[136,]   97  103
[137,]   69  104
[138,] -158  112
[139,]  111  123
[140,]  105  133
[141,]  110  124
[142,]  115  135
[143,]  121  140
[144,]  102  130
[145,]  126  131
[146,]  132  134
[147,]  120  138
[148,]   96  137
[149,]  -60  114
[150,]  116  122
[151,]   93  119
[152,]  106  144
[153,]   75  146
[154,]  -72  136
[155,]  113  147
[156,]  139  155
[157,]   77  128
[158,]  142  153
[159,]  -74  151
[160,]  -97  141
[161,] -111  125
[162,]  127  152
[163,]  143  154
[164,]  145  158
[165,]  150  163
[166,]  156  157
[167,]  148  149
[168,] -122  159
[169,]  162  165
[170,]  160  166
[171,]  129  161
[172,]  164  171
[173,]   39  170
[174,]  168  169
[175,]  167  172
[176,]  173  174
[177,]  175  176

$height
  [1]  1.160843  1.188251  1.205954  1.222071  1.241887  1.264851  1.284271
  [8]  1.288161  1.296828  1.331911  1.340696  1.348374  1.358855  1.361478
 [15]  1.363560  1.380142  1.382870  1.433903  1.440518  1.453793  1.467187
 [22]  1.473935  1.482344  1.508987  1.534226  1.550962  1.574982  1.576543
 [29]  1.580445  1.592676  1.603496  1.684904  1.693967  1.709760  1.730825
 [36]  1.733150  1.748831  1.752004  1.778945  1.782307  1.790419  1.795550
 [43]  1.809520  1.814755  1.819535  1.821081  1.821547  1.825128  1.846338
 [50]  1.860170  1.863070  1.874591  1.877544  1.912972  1.921731  1.951311
 [57]  1.963937  1.976797  1.979492  1.987607  1.992191  1.998042  2.020043
 [64]  2.020370  2.029161  2.033331  2.069074  2.078776  2.087748  2.093797
 [71]  2.110617  2.150431  2.182785  2.203353  2.211630  2.215128  2.224848
 [78]  2.226880  2.261274  2.295005  2.302508  2.302972  2.310072  2.322844
 [85]  2.334877  2.378366  2.379698  2.382467  2.387313  2.412048  2.413190
 [92]  2.418441  2.443739  2.446711  2.452477  2.478849  2.479222  2.486449
 [99]  2.529816  2.540321  2.565125  2.643328  2.647521  2.658401  2.660328
[106]  2.725115  2.745806  2.751642  2.831830  2.869085  2.881377  2.886100
[113]  2.923773  2.948097  2.956011  2.961673  3.029478  3.034972  3.043920
[120]  3.115118  3.130146  3.161686  3.190307  3.230435  3.238763  3.256907
[127]  3.276538  3.279362  3.327533  3.342714  3.344161  3.371468  3.399312
[134]  3.427151  3.446690  3.620525  3.644193  3.653005  3.662574  3.727933
[141]  3.768024  3.792415  3.844037  3.845727  3.954507  4.002263  4.077635
[148]  4.095833  4.154695  4.160830  4.304737  4.317613  4.371644  4.514860
[155]  4.597476  4.649758  4.756611  5.005163  5.077795  5.082824  5.087252
[162]  5.116238  5.241364  5.287665  5.752727  5.765116  5.873639  6.364518
[169]  6.558656  6.728433  6.983887  7.496191  7.640356  8.246435  8.906154
[176]  9.783151 11.179959

$order
  [1]  62  61  69  65  87  71  78  60  63  77  76 101  33  66  27  58  37  35
 [19]  38  22  36  24  25  42  44   2  28  39   9  47   1  21  41  57  10  48
 [37]  45  55  20  40   8  46  14  15  11  32  50   6  19  43  59   4  53  31
 [55]   3  49  56   7  23  30  52  12  13  96  70  79 111  51  67 159 160  97
 [73] 131 133 132 134 153 151 150 152 145 176 177 148 161 168 172 154 157 165
 [91] 173 149 175 170 178 167 169 162 141 143 140 163  84 144 139 166 158 156
[109] 174 137 138 155 135 136 147 119 146 142 164 171 122  74  34  16  54  17
[127]  18  26   5  29 100 116  83  88 114  90 115 106  93 108  89  91  92 113
[145] 128 124 125 130  80 123  68 102 107 105 117  73 118  94  95  81  98  82
[163]  86 103 112 126 127 129 120 104 109  72 121  85 110  75  64  99

$labels
NULL

$method
[1] "complete"

$call
hclust(d = complete_distmatrix, method = "complete")
# [4] 덴드로그램 시각화
plot(hc_complete,
     main = "Complete Linkage",
     cex = 0.4)  # 텍스트 크기 줄임

3-3) Average Linkage 방식 - 특징: 두 클러스터 간 모든 거리의 평균값으로 병합 - 장점: 이상치에 덜 민감하고 안정적인 클러스터 구조 형성 - 단점: 거리 평균 계산으로 연산량이 많고 처리 속도가 느릴 수 있음

# [1] 거리 계산 (표준화된 독립 변수 집합 x_scaled 사용)
# Average Linkage는 두 클러스터 간의 '평균 거리'를 기준으로 병합함
# 클러스터 간의 모든 점 쌍의 거리를 평균 내기 위해 우선 거리 행렬 필요
average_distmatrix <- dist(x_scaled)

# [2] hclust()로 average linkage 방식 클러스터링 수행
# method = "average" 옵션을 사용하여 계층적 클러스터링 실행
hc_average <- hclust(average_distmatrix, method = "average")

# [3] 클러스터 병합 정보 확인
# head()로 결과 객체를 살펴보면 병합 순서($merge), 거리($height), 순서($order) 확인 가능
head(hc_average)
$merge
       [,1] [,2]
  [1,]  -10  -48
  [2,] -132 -134
  [3,]  -12  -13
  [4,]  -16  -54
  [5,]  -93 -108
  [6,]  -35  -38
  [7,]   -1  -21
  [8,]  -17  -18
  [9,] -165 -173
 [10,]  -23  -30
 [11,]  -41  -57
 [12,] -105 -117
 [13,]  -24  -25
 [14,]  -28  -39
 [15,] -141 -143
 [16,]  -64  -99
 [17,]  -27  -58
 [18,] -112 -126
 [19,] -164 -171
 [20,] -149 -175
 [21,]  -83  -88
 [22,]  -91  -92
 [23,] -140 -163
 [24,]  -11  -32
 [25,] -107   12
 [26,] -139 -166
 [27,]  -36   13
 [28,]    7   11
 [29,] -148 -161
 [30,]   -6  -19
 [31,] -156 -174
 [32,]    5   22
 [33,] -168 -172
 [34,]  -81  -98
 [35,]   -7   10
 [36,]   15   23
 [37,]    4    8
 [38,] -167 -169
 [39,] -150 -152
 [40,]  -43  -59
 [41,] -103   18
 [42,] -135 -136
 [43,]  -45    1
 [44,]  -37    6
 [45,] -133    2
 [46,]  -49  -56
 [47,] -157   20
 [48,] -159 -160
 [49,] -104 -109
 [50,]  -42  -44
 [51,]  -52    3
 [52,]  -20  -40
 [53,]  -82  -86
 [54,] -176 -177
 [55,]  -50   30
 [56,]  -85 -110
 [57,]  -68   25
 [58,]  -55   43
 [59,] -127 -129
 [60,] -162   36
 [61,]  -87   21
 [62,]   -4  -53
 [63,]  -89  -90
 [64,] -151   39
 [65,]   -5  -29
 [66,]    9   47
 [67,] -102   57
 [68,] -146   19
 [69,]   17   44
 [70,] -115   41
 [71,]   35   51
 [72,]   -3   46
 [73,] -144   26
 [74,]   24   55
 [75,]   34   53
 [76,]   40   62
 [77,]  -31   72
 [78,]   -2   14
 [79,] -155   42
 [80,]   28   58
 [81,]  -61  -69
 [82,]   59   70
 [83,]   -8   37
 [84,] -142   68
 [85,]   61   63
 [86,]   -9   71
 [87,]  -94  -95
 [88,]   27   69
 [89,]  -63  -77
 [90,]  -14  -15
 [91,] -137 -138
 [92,]  -34   83
 [93,]   29   31
 [94,]  -84   73
 [95,]   33   66
 [96,] -121   56
 [97,]   49   67
 [98,]  -33   86
 [99,]  -46   50
[100,]  -76 -101
[101,] -114   85
[102,]   75   87
[103,]  -62   81
[104,] -154   54
[105,] -120 -130
[106,]  -80 -123
[107,] -118   82
[108,] -178   38
[109,] -106   32
[110,]   74   76
[111,]   65   88
[112,]   45   84
[113,]  -22   99
[114,]   78   98
[115,]  -47   52
[116,]   93   94
[117,]   97  102
[118,] -170  108
[119,]  -75   16
[120,]   92  111
[121,]  -65 -113
[122,]   89  100
[123,]  -71  -78
[124,] -145  112
[125,]   80  110
[126,]   95  104
[127,] -153   64
[128,]  101  109
[129,]  -73  107
[130,]  -70  -79
[131,]   77  125
[132,]   91  116
[133,]  -66   96
[134,]  117  129
[135,]  113  115
[136,] -158   60
[137,]  114  120
[138,]  118  126
[139,] -124 -125
[140,]  132  136
[141,]  131  137
[142,] -131  124
[143,] -119  105
[144,]  123  142
[145,]  -96  130
[146,]  -51   90
[147,]  127  138
[148,]  119  133
[149,]  128  134
[150,] -100 -116
[151,]   79  103
[152,] -128  106
[153,]  135  141
[154,] -147  140
[155,]  143  149
[156,]  147  154
[157,]  122  155
[158,]  144  156
[159,]  148  157
[160,]  -26 -122
[161,]  146  153
[162,] -111  139
[163,]  121  152
[164,]  151  158
[165,]  159  163
[166,]  150  165
[167,]  -72  166
[168,]  -74  160
[169,]  -67  167
[170,]  -97  145
[171,]  161  169
[172,]   48  164
[173,]  162  171
[174,]  172  173
[175,]  170  174
[176,]  168  175
[177,]  -60  176

$height
  [1] 1.160843 1.188251 1.205954 1.222071 1.241887 1.264851 1.284271 1.288161
  [9] 1.296828 1.331911 1.340696 1.348374 1.358855 1.361478 1.363560 1.380142
 [17] 1.382870 1.433903 1.440518 1.453793 1.467187 1.473935 1.482344 1.508987
 [25] 1.530100 1.550962 1.551881 1.570912 1.574982 1.576543 1.580445 1.588214
 [33] 1.592676 1.603496 1.634388 1.640453 1.679254 1.684904 1.693967 1.709760
 [41] 1.712311 1.730825 1.735627 1.741738 1.750584 1.752004 1.770885 1.778945
 [49] 1.782307 1.790419 1.807244 1.814755 1.819535 1.821081 1.821347 1.825128
 [57] 1.839773 1.856926 1.863070 1.868751 1.871118 1.877544 1.881028 1.906574
 [65] 1.912972 1.919825 1.921276 1.933496 1.936210 1.955549 1.965108 1.973616
 [73] 1.999579 2.017841 2.023095 2.040774 2.051350 2.056704 2.072457 2.078201
 [81] 2.093797 2.115481 2.133325 2.165449 2.174407 2.180914 2.182785 2.199440
 [89] 2.203353 2.211630 2.215128 2.226932 2.232088 2.232920 2.244622 2.248898
 [97] 2.261002 2.267432 2.288508 2.302972 2.309069 2.342542 2.372070 2.378695
[105] 2.399616 2.413190 2.416871 2.422047 2.443222 2.454916 2.455320 2.488505
[113] 2.496342 2.499366 2.530338 2.562234 2.570466 2.618701 2.627551 2.647779
[121] 2.647854 2.650523 2.658401 2.675507 2.687076 2.701771 2.702138 2.726782
[129] 2.727351 2.751642 2.755358 2.780191 2.790834 2.835997 2.849159 2.851152
[137] 2.915577 2.948472 2.961673 2.978134 3.006930 3.059933 3.118477 3.125117
[145] 3.149236 3.185518 3.205299 3.210608 3.215436 3.276538 3.288681 3.290911
[153] 3.364212 3.474018 3.496397 3.537510 3.545044 3.636489 3.771276 3.849549
[161] 3.924622 3.952582 3.998080 4.131329 4.175701 4.306565 4.483391 4.534640
[169] 4.546831 4.912946 4.953069 5.162649 5.425214 5.640434 6.053094 6.335260
[177] 6.762454

$order
  [1]  60  74  26 122  97  96  70  79 159 160 155 135 136  62  61  69  71  78
 [19] 131 145 133 132 134 142 146 164 171 153 151 150 152 170 178 167 169 168
 [37] 172 165 173 157 149 175 154 176 177 147 137 138 148 161 156 174  84 144
 [55] 139 166 158 162 141 143 140 163 111 124 125  51  14  15  22  46  42  44
 [73]  47  20  40  31   3  49  56   1  21  41  57  55  45  10  48  11  32  50
 [91]   6  19  43  59   4  53   2  28  39  33   9   7  23  30  52  12  13  34
[109]   8  16  54  17  18   5  29  36  24  25  27  58  37  35  38  67  72 100
[127] 116  75  64  99  66 121  85 110  63  77  76 101 119 120 130 114  87  83
[145]  88  89  90 106  93 108  91  92 104 109 102  68 107 105 117  81  98  82
[163]  86  94  95  73 118 127 129 115 103 112 126  65 113 128  80 123

$labels
NULL

$method
[1] "average"

$call
hclust(d = average_distmatrix, method = "average")
# [4] 덴드로그램 시각화
# 평균 링크 방식을 통해 생성된 계층적 클러스터 결과를 트리 형태로 시각화
# cex는 덴드로그램의 숫자 텍스트 크기 설정
plot(hc_average,
     main = "Average Linkage",  # 그래프 제목
     cex = 0.4)                  # 텍스트 크기 축소 (데이터가 많을 경우)

3-4) 세 가지 Linkage 방식의 클러스터 병합 구조 비교 (head() 활용)

### 3-4) 세 가지 linkage 방식 결과 비교 (`head()`로 클러스터 병합 정보 확인)

# Single Linkage 방식 결과 확인
# - 병합 순서, 병합 거리, 클러스터 순서를 확인하여 구조 파악
head(hc_single)
$merge
       [,1] [,2]
  [1,]  -10  -48
  [2,] -132 -134
  [3,]  -12  -13
  [4,]  -16  -54
  [5,]  -93 -108
  [6,]  -35  -38
  [7,]   -1  -21
  [8,]  -17  -18
  [9,] -165 -173
 [10,]  -57    7
 [11,]  -23  -30
 [12,]  -41   10
 [13,] -105 -117
 [14,]  -24  -25
 [15,]  -28  -39
 [16,] -141 -143
 [17,]  -36   14
 [18,] -163   16
 [19,]  -64  -99
 [20,]  -27  -58
 [21,]  -91    5
 [22,]    4   20
 [23,] -112 -126
 [24,] -164 -171
 [25,]   -7   11
 [26,] -149 -175
 [27,]  -92   21
 [28,]  -83  -88
 [29,]  -55   12
 [30,]    8   22
 [31,] -140   18
 [32,] -157   26
 [33,]  -45    1
 [34,] -133    2
 [35,]  -11  -32
 [36,]  -89   27
 [37,] -107   13
 [38,]  -68   37
 [39,] -139 -166
 [40,]   29   33
 [41,]    9   32
 [42,] -146   24
 [43,]  -87   28
 [44,]    3   15
 [45,] -148 -161
 [46,]   -6  -19
 [47,] -168   41
 [48,] -156 -174
 [49,]  -52   44
 [50,]   25   40
 [51,]   49   50
 [52,] -172   47
 [53,]  -53   46
 [54,]   30   53
 [55,]  -81  -98
 [56,]   17   51
 [57,] -103   23
 [58,]  -37    6
 [59,]  -82   38
 [60,]  -90   43
 [61,] -162   31
 [62,]   45   52
 [63,]   56   58
 [64,] -127   57
 [65,] -167 -169
 [66,] -150 -152
 [67,] -115   64
 [68,]   34   42
 [69,]  -50   35
 [70,]  -43  -59
 [71,]   54   69
 [72,] -135 -136
 [73,]   -4   70
 [74,] -176   66
 [75,] -102   59
 [76,] -104   75
 [77,]  -49  -56
 [78,]   48   62
 [79,]   -9   63
 [80,]   71   79
 [81,]   73   80
 [82,]   65   78
 [83,] -159 -160
 [84,] -109   76
 [85,]   -8   81
 [86,]  -42  -44
 [87,]   36   60
 [88,]  -20  -40
 [89,]  -86   84
 [90,] -177   74
 [91,]  -85 -110
 [92,]   55   89
 [93,] -121   67
 [94,]  -29   85
 [95,]   77   94
 [96,] -151   90
 [97,]   -2   95
 [98,]   39   72
 [99,] -129   93
[100,]  -33   97
[101,]   -5  100
[102,] -155   98
[103,]   -3  101
[104,] -118   92
[105,]   99  104
[106,]  -34  103
[107,]   87  105
[108,] -144  102
[109,]   88  106
[110,] -114  107
[111,]  109  110
[112,]   82  108
[113,] -154  112
[114,]  -94  111
[115,]  -31  114
[116,] -142   68
[117,]   91  115
[118,] -101  117
[119,]  -22   86
[120,]   61  116
[121,]  -77  118
[122,]   96  113
[123,]  -65  121
[124,] -145  120
[125,]  -61  -69
[126,] -120  123
[127,]  -26  126
[128,] -178  122
[129,]  124  128
[130,]  -66  127
[131,]  -84  129
[132,]  -47  130
[133,] -153  131
[134,]  -95  132
[135,] -131  133
[136,]  -63  134
[137,]  119  136
[138,]   19  137
[139,]  -14  -15
[140,]  -46  138
[141,] -137 -138
[142,] -147  135
[143,]  -76  140
[144,]  -73  143
[145,]  -62  125
[146,] -106  144
[147,]  139  146
[148,]  142  145
[149,]  141  148
[150,] -170  149
[151,] -130  147
[152,]  -80 -123
[153,]  150  151
[154,] -158  153
[155,]  -75  154
[156,]  -67  155
[157,]  -78  156
[158,]  -71  157
[159,] -119  158
[160,]  -51  159
[161,] -113  160
[162,]  152  161
[163,]  -70  -79
[164,] -100  162
[165,]  -72  164
[166,] -124  165
[167,] -128  166
[168,] -116  167
[169,] -125  168
[170,]  -96  163
[171,]   83  169
[172,]  -97  171
[173,] -111  172
[174,]  -60  173
[175,] -122  174
[176,]  -74  175
[177,]  170  176

$height
  [1] 1.160843 1.188251 1.205954 1.222071 1.241887 1.264851 1.284271 1.288161
  [9] 1.296828 1.324025 1.331911 1.340696 1.348374 1.358855 1.361478 1.363560
 [17] 1.370611 1.378732 1.380142 1.382870 1.387890 1.418248 1.433903 1.440518
 [25] 1.447228 1.453793 1.457268 1.467187 1.467545 1.471205 1.482344 1.482473
 [33] 1.494457 1.508977 1.508987 1.520496 1.525974 1.545223 1.550962 1.556337
 [41] 1.556527 1.558535 1.567036 1.568580 1.574982 1.576543 1.578079 1.580445
 [49] 1.581156 1.582212 1.589026 1.592676 1.599000 1.600496 1.603496 1.606328
 [57] 1.615102 1.623307 1.634914 1.641285 1.650533 1.653828 1.671531 1.673727
 [65] 1.684904 1.693967 1.703682 1.707316 1.709144 1.709760 1.720964 1.730825
 [73] 1.733772 1.739964 1.742057 1.745761 1.752004 1.753828 1.756444 1.761992
 [81] 1.762220 1.763503 1.778945 1.782307 1.787060 1.790419 1.793249 1.814755
 [89] 1.819535 1.821081 1.825128 1.825172 1.826123 1.831551 1.839258 1.849210
 [97] 1.852135 1.852611 1.863070 1.909557 1.912972 1.920066 1.926862 1.938448
[105] 1.940164 1.950542 1.967276 1.969996 1.970307 1.971198 1.977704 1.986412
[113] 1.987607 2.006050 2.007469 2.008832 2.018574 2.044711 2.070141 2.078656
[121] 2.079317 2.082879 2.087748 2.088956 2.093797 2.095389 2.130095 2.137666
[129] 2.145495 2.148482 2.148840 2.154930 2.165547 2.182785 2.202890 2.203353
[137] 2.203755 2.208295 2.211630 2.211859 2.215128 2.217818 2.220080 2.265276
[145] 2.265291 2.285815 2.329241 2.356219 2.357356 2.393491 2.398171 2.413190
[153] 2.419783 2.433901 2.442622 2.459714 2.514725 2.521795 2.542696 2.594692
[161] 2.647854 2.732751 2.751642 2.767648 2.809071 2.821419 2.855266 2.927361
[169] 2.961673 2.970939 3.000725 3.302767 3.419517 3.630279 3.849549 3.896609
[177] 3.992191

$order
  [1]  96  70  79  74 122  60 111  97 159 160 125 116 128 124  72 100  80 123
 [19] 113  51 119  71  78  67  75 158 170 137 138 147 131 153  84 145 162 140
 [37] 163 141 143 142 133 132 134 146 164 171 178 151 177 176 150 152 154 167
 [55] 169 156 174 148 161 172 168 165 173 157 149 175 144 155 139 166 135 136
 [73]  62  61  69 130  14  15 106  73  76  46  64  99  22  42  44  63  95  47
 [91]  66  26 120  65  77 101  85 110  31  94  20  40  34   3   5  33   2  49
[109]  56  29   8   4  43  59  17  18  16  54  27  58  53   6  19  50  11  32
[127]   9  36  24  25  52  12  13  28  39   7  23  30  55  41  57   1  21  45
[145]  10  48  37  35  38 114  89  92  91  93 108  90  87  83  88 129 121 115
[163] 127 103 112 126 118  81  98  86 109 104 102  82  68 107 105 117

$labels
NULL

$method
[1] "single"

$call
hclust(d = single_distmatrix, method = "single")
# Complete Linkage 방식 결과 확인
# - 병합 높이가 상대적으로 크며, 고르게 나뉜 클러스터 특성 파악 가능
head(hc_complete)
$merge
       [,1] [,2]
  [1,]  -10  -48
  [2,] -132 -134
  [3,]  -12  -13
  [4,]  -16  -54
  [5,]  -93 -108
  [6,]  -35  -38
  [7,]   -1  -21
  [8,]  -17  -18
  [9,] -165 -173
 [10,]  -23  -30
 [11,]  -41  -57
 [12,] -105 -117
 [13,]  -24  -25
 [14,]  -28  -39
 [15,] -141 -143
 [16,]  -64  -99
 [17,]  -27  -58
 [18,] -112 -126
 [19,] -164 -171
 [20,] -149 -175
 [21,]  -83  -88
 [22,]  -91  -92
 [23,] -140 -163
 [24,]  -11  -32
 [25,] -107   12
 [26,] -139 -166
 [27,] -148 -161
 [28,]   -6  -19
 [29,] -156 -174
 [30,] -168 -172
 [31,]  -81  -98
 [32,] -167 -169
 [33,] -150 -152
 [34,]  -43  -59
 [35,] -135 -136
 [36,]  -36   13
 [37,]   15   23
 [38,]  -49  -56
 [39,] -159 -160
 [40,] -104 -109
 [41,]  -42  -44
 [42,]  -89   22
 [43,] -103   18
 [44,]  -20  -40
 [45,]  -82  -86
 [46,] -176 -177
 [47,]   -7   10
 [48,]  -85 -110
 [49,]  -45  -55
 [50,]  -37    6
 [51,] -127 -129
 [52,]    7   11
 [53,]   -4  -53
 [54,]   -5  -29
 [55,]  -50   28
 [56,]    4    8
 [57,] -151   33
 [58,]    1   49
 [59,] -102   25
 [60,] -154 -157
 [61,] -133    2
 [62,]  -90 -115
 [63,] -162   37
 [64,]   -3   38
 [65,] -144   26
 [66,]  -52    3
 [67,] -142   19
 [68,]   17   50
 [69,]  -65  -87
 [70,]  -61  -69
 [71,]  -31   64
 [72,]  -68   59
 [73,]  -94  -95
 [74,]  -63  -77
 [75,]  -14  -15
 [76,] -137 -138
 [77,] -155   35
 [78,]   47   66
 [79,]   -2   14
 [80,]   24   55
 [81,]    9   20
 [82,]  -76 -101
 [83,]   43   51
 [84,]   -8  -46
 [85,]   -9  -47
 [86,]  -33  -66
 [87,]    5   42
 [88,] -120   40
 [89,]  -84   65
 [90,]   31   45
 [91,]  -80 -123
 [92,] -146   67
 [93,]  -34   56
 [94,]   34   53
 [95,]  -22   36
 [96,]  -62   70
 [97,] -121   48
 [98,] -178   32
 [99,] -114   62
[100,]  -73 -118
[101,]   27   30
[102,] -106   87
[103,]  -75   16
[104,]  -71  -78
[105,]   73   90
[106,]   21   99
[107,]   52   58
[108,]  -70  -79
[109,]   60   81
[110,] -131   61
[111,] -145   46
[112,]   29   76
[113,] -170   98
[114,]   74   82
[115,]   85  107
[116,] -124 -125
[117,]   68   95
[118,] -119   92
[119,]  -26   54
[120,]   63   89
[121,]   72  100
[122,] -130   91
[123,]  101  109
[124,] -153   57
[125,]  -51  -67
[126,]   86  117
[127,] -100 -116
[128,] -147  118
[129,]  -96  108
[130,] -113 -128
[131,]   41   79
[132,]   80   94
[133,]   83   88
[134,]   71   78
[135,]   44   84
[136,]   97  103
[137,]   69  104
[138,] -158  112
[139,]  111  123
[140,]  105  133
[141,]  110  124
[142,]  115  135
[143,]  121  140
[144,]  102  130
[145,]  126  131
[146,]  132  134
[147,]  120  138
[148,]   96  137
[149,]  -60  114
[150,]  116  122
[151,]   93  119
[152,]  106  144
[153,]   75  146
[154,]  -72  136
[155,]  113  147
[156,]  139  155
[157,]   77  128
[158,]  142  153
[159,]  -74  151
[160,]  -97  141
[161,] -111  125
[162,]  127  152
[163,]  143  154
[164,]  145  158
[165,]  150  163
[166,]  156  157
[167,]  148  149
[168,] -122  159
[169,]  162  165
[170,]  160  166
[171,]  129  161
[172,]  164  171
[173,]   39  170
[174,]  168  169
[175,]  167  172
[176,]  173  174
[177,]  175  176

$height
  [1]  1.160843  1.188251  1.205954  1.222071  1.241887  1.264851  1.284271
  [8]  1.288161  1.296828  1.331911  1.340696  1.348374  1.358855  1.361478
 [15]  1.363560  1.380142  1.382870  1.433903  1.440518  1.453793  1.467187
 [22]  1.473935  1.482344  1.508987  1.534226  1.550962  1.574982  1.576543
 [29]  1.580445  1.592676  1.603496  1.684904  1.693967  1.709760  1.730825
 [36]  1.733150  1.748831  1.752004  1.778945  1.782307  1.790419  1.795550
 [43]  1.809520  1.814755  1.819535  1.821081  1.821547  1.825128  1.846338
 [50]  1.860170  1.863070  1.874591  1.877544  1.912972  1.921731  1.951311
 [57]  1.963937  1.976797  1.979492  1.987607  1.992191  1.998042  2.020043
 [64]  2.020370  2.029161  2.033331  2.069074  2.078776  2.087748  2.093797
 [71]  2.110617  2.150431  2.182785  2.203353  2.211630  2.215128  2.224848
 [78]  2.226880  2.261274  2.295005  2.302508  2.302972  2.310072  2.322844
 [85]  2.334877  2.378366  2.379698  2.382467  2.387313  2.412048  2.413190
 [92]  2.418441  2.443739  2.446711  2.452477  2.478849  2.479222  2.486449
 [99]  2.529816  2.540321  2.565125  2.643328  2.647521  2.658401  2.660328
[106]  2.725115  2.745806  2.751642  2.831830  2.869085  2.881377  2.886100
[113]  2.923773  2.948097  2.956011  2.961673  3.029478  3.034972  3.043920
[120]  3.115118  3.130146  3.161686  3.190307  3.230435  3.238763  3.256907
[127]  3.276538  3.279362  3.327533  3.342714  3.344161  3.371468  3.399312
[134]  3.427151  3.446690  3.620525  3.644193  3.653005  3.662574  3.727933
[141]  3.768024  3.792415  3.844037  3.845727  3.954507  4.002263  4.077635
[148]  4.095833  4.154695  4.160830  4.304737  4.317613  4.371644  4.514860
[155]  4.597476  4.649758  4.756611  5.005163  5.077795  5.082824  5.087252
[162]  5.116238  5.241364  5.287665  5.752727  5.765116  5.873639  6.364518
[169]  6.558656  6.728433  6.983887  7.496191  7.640356  8.246435  8.906154
[176]  9.783151 11.179959

$order
  [1]  62  61  69  65  87  71  78  60  63  77  76 101  33  66  27  58  37  35
 [19]  38  22  36  24  25  42  44   2  28  39   9  47   1  21  41  57  10  48
 [37]  45  55  20  40   8  46  14  15  11  32  50   6  19  43  59   4  53  31
 [55]   3  49  56   7  23  30  52  12  13  96  70  79 111  51  67 159 160  97
 [73] 131 133 132 134 153 151 150 152 145 176 177 148 161 168 172 154 157 165
 [91] 173 149 175 170 178 167 169 162 141 143 140 163  84 144 139 166 158 156
[109] 174 137 138 155 135 136 147 119 146 142 164 171 122  74  34  16  54  17
[127]  18  26   5  29 100 116  83  88 114  90 115 106  93 108  89  91  92 113
[145] 128 124 125 130  80 123  68 102 107 105 117  73 118  94  95  81  98  82
[163]  86 103 112 126 127 129 120 104 109  72 121  85 110  75  64  99

$labels
NULL

$method
[1] "complete"

$call
hclust(d = complete_distmatrix, method = "complete")
# Average Linkage 방식 결과 확인
# - 병합 순서와 거리 모두 Single 방식과 유사하지만, 평균값을 사용해 더 균형 잡힌 결과
head(hc_average)
$merge
       [,1] [,2]
  [1,]  -10  -48
  [2,] -132 -134
  [3,]  -12  -13
  [4,]  -16  -54
  [5,]  -93 -108
  [6,]  -35  -38
  [7,]   -1  -21
  [8,]  -17  -18
  [9,] -165 -173
 [10,]  -23  -30
 [11,]  -41  -57
 [12,] -105 -117
 [13,]  -24  -25
 [14,]  -28  -39
 [15,] -141 -143
 [16,]  -64  -99
 [17,]  -27  -58
 [18,] -112 -126
 [19,] -164 -171
 [20,] -149 -175
 [21,]  -83  -88
 [22,]  -91  -92
 [23,] -140 -163
 [24,]  -11  -32
 [25,] -107   12
 [26,] -139 -166
 [27,]  -36   13
 [28,]    7   11
 [29,] -148 -161
 [30,]   -6  -19
 [31,] -156 -174
 [32,]    5   22
 [33,] -168 -172
 [34,]  -81  -98
 [35,]   -7   10
 [36,]   15   23
 [37,]    4    8
 [38,] -167 -169
 [39,] -150 -152
 [40,]  -43  -59
 [41,] -103   18
 [42,] -135 -136
 [43,]  -45    1
 [44,]  -37    6
 [45,] -133    2
 [46,]  -49  -56
 [47,] -157   20
 [48,] -159 -160
 [49,] -104 -109
 [50,]  -42  -44
 [51,]  -52    3
 [52,]  -20  -40
 [53,]  -82  -86
 [54,] -176 -177
 [55,]  -50   30
 [56,]  -85 -110
 [57,]  -68   25
 [58,]  -55   43
 [59,] -127 -129
 [60,] -162   36
 [61,]  -87   21
 [62,]   -4  -53
 [63,]  -89  -90
 [64,] -151   39
 [65,]   -5  -29
 [66,]    9   47
 [67,] -102   57
 [68,] -146   19
 [69,]   17   44
 [70,] -115   41
 [71,]   35   51
 [72,]   -3   46
 [73,] -144   26
 [74,]   24   55
 [75,]   34   53
 [76,]   40   62
 [77,]  -31   72
 [78,]   -2   14
 [79,] -155   42
 [80,]   28   58
 [81,]  -61  -69
 [82,]   59   70
 [83,]   -8   37
 [84,] -142   68
 [85,]   61   63
 [86,]   -9   71
 [87,]  -94  -95
 [88,]   27   69
 [89,]  -63  -77
 [90,]  -14  -15
 [91,] -137 -138
 [92,]  -34   83
 [93,]   29   31
 [94,]  -84   73
 [95,]   33   66
 [96,] -121   56
 [97,]   49   67
 [98,]  -33   86
 [99,]  -46   50
[100,]  -76 -101
[101,] -114   85
[102,]   75   87
[103,]  -62   81
[104,] -154   54
[105,] -120 -130
[106,]  -80 -123
[107,] -118   82
[108,] -178   38
[109,] -106   32
[110,]   74   76
[111,]   65   88
[112,]   45   84
[113,]  -22   99
[114,]   78   98
[115,]  -47   52
[116,]   93   94
[117,]   97  102
[118,] -170  108
[119,]  -75   16
[120,]   92  111
[121,]  -65 -113
[122,]   89  100
[123,]  -71  -78
[124,] -145  112
[125,]   80  110
[126,]   95  104
[127,] -153   64
[128,]  101  109
[129,]  -73  107
[130,]  -70  -79
[131,]   77  125
[132,]   91  116
[133,]  -66   96
[134,]  117  129
[135,]  113  115
[136,] -158   60
[137,]  114  120
[138,]  118  126
[139,] -124 -125
[140,]  132  136
[141,]  131  137
[142,] -131  124
[143,] -119  105
[144,]  123  142
[145,]  -96  130
[146,]  -51   90
[147,]  127  138
[148,]  119  133
[149,]  128  134
[150,] -100 -116
[151,]   79  103
[152,] -128  106
[153,]  135  141
[154,] -147  140
[155,]  143  149
[156,]  147  154
[157,]  122  155
[158,]  144  156
[159,]  148  157
[160,]  -26 -122
[161,]  146  153
[162,] -111  139
[163,]  121  152
[164,]  151  158
[165,]  159  163
[166,]  150  165
[167,]  -72  166
[168,]  -74  160
[169,]  -67  167
[170,]  -97  145
[171,]  161  169
[172,]   48  164
[173,]  162  171
[174,]  172  173
[175,]  170  174
[176,]  168  175
[177,]  -60  176

$height
  [1] 1.160843 1.188251 1.205954 1.222071 1.241887 1.264851 1.284271 1.288161
  [9] 1.296828 1.331911 1.340696 1.348374 1.358855 1.361478 1.363560 1.380142
 [17] 1.382870 1.433903 1.440518 1.453793 1.467187 1.473935 1.482344 1.508987
 [25] 1.530100 1.550962 1.551881 1.570912 1.574982 1.576543 1.580445 1.588214
 [33] 1.592676 1.603496 1.634388 1.640453 1.679254 1.684904 1.693967 1.709760
 [41] 1.712311 1.730825 1.735627 1.741738 1.750584 1.752004 1.770885 1.778945
 [49] 1.782307 1.790419 1.807244 1.814755 1.819535 1.821081 1.821347 1.825128
 [57] 1.839773 1.856926 1.863070 1.868751 1.871118 1.877544 1.881028 1.906574
 [65] 1.912972 1.919825 1.921276 1.933496 1.936210 1.955549 1.965108 1.973616
 [73] 1.999579 2.017841 2.023095 2.040774 2.051350 2.056704 2.072457 2.078201
 [81] 2.093797 2.115481 2.133325 2.165449 2.174407 2.180914 2.182785 2.199440
 [89] 2.203353 2.211630 2.215128 2.226932 2.232088 2.232920 2.244622 2.248898
 [97] 2.261002 2.267432 2.288508 2.302972 2.309069 2.342542 2.372070 2.378695
[105] 2.399616 2.413190 2.416871 2.422047 2.443222 2.454916 2.455320 2.488505
[113] 2.496342 2.499366 2.530338 2.562234 2.570466 2.618701 2.627551 2.647779
[121] 2.647854 2.650523 2.658401 2.675507 2.687076 2.701771 2.702138 2.726782
[129] 2.727351 2.751642 2.755358 2.780191 2.790834 2.835997 2.849159 2.851152
[137] 2.915577 2.948472 2.961673 2.978134 3.006930 3.059933 3.118477 3.125117
[145] 3.149236 3.185518 3.205299 3.210608 3.215436 3.276538 3.288681 3.290911
[153] 3.364212 3.474018 3.496397 3.537510 3.545044 3.636489 3.771276 3.849549
[161] 3.924622 3.952582 3.998080 4.131329 4.175701 4.306565 4.483391 4.534640
[169] 4.546831 4.912946 4.953069 5.162649 5.425214 5.640434 6.053094 6.335260
[177] 6.762454

$order
  [1]  60  74  26 122  97  96  70  79 159 160 155 135 136  62  61  69  71  78
 [19] 131 145 133 132 134 142 146 164 171 153 151 150 152 170 178 167 169 168
 [37] 172 165 173 157 149 175 154 176 177 147 137 138 148 161 156 174  84 144
 [55] 139 166 158 162 141 143 140 163 111 124 125  51  14  15  22  46  42  44
 [73]  47  20  40  31   3  49  56   1  21  41  57  55  45  10  48  11  32  50
 [91]   6  19  43  59   4  53   2  28  39  33   9   7  23  30  52  12  13  34
[109]   8  16  54  17  18   5  29  36  24  25  27  58  37  35  38  67  72 100
[127] 116  75  64  99  66 121  85 110  63  77  76 101 119 120 130 114  87  83
[145]  88  89  90 106  93 108  91  92 104 109 102  68 107 105 117  81  98  82
[163]  86  94  95  73 118 127 129 115 103 112 126  65 113 128  80 123

$labels
NULL

$method
[1] "average"

$call
hclust(d = average_distmatrix, method = "average")

3-6) 덴드로그램 병합 비교 시각화: Single / Complete / Average

# [0] 세 방식별 병합 높이 정보 (head에서 확인한 결과 기반)
h_single_first <- 1.160843
h_single_cut   <- 1.264851

h_complete_first <- 3.068951
h_complete_cut   <- 4.111052

h_average_first <- 1.160843
h_average_cut   <- 1.264851

# [1] Single Linkage 덴드로그램
plot(hc_single,
     main = "Single Linkage",
     cex = 0.5)
abline(h = h_single_first, col = "red", lwd = 2)
abline(h = h_single_cut, col = "blue", lwd = 2)
text(x = 0, y = h_single_first, labels = "1st: 1.16", col = "red", pos = 4, cex = 0.8)
text(x = 0, y = h_single_cut,   labels = "Cut: 1.26", col = "blue", pos = 4, cex = 0.8)

# [2] Complete Linkage 덴드로그램
plot(hc_complete,
     main = "Complete Linkage",
     cex = 0.5)
abline(h = h_complete_first, col = "red", lwd = 2)
abline(h = h_complete_cut, col = "blue", lwd = 2)
text(x = 0, y = h_complete_first, labels = "1st: 3.07", col = "red", pos = 4, cex = 0.8)
text(x = 0, y = h_complete_cut,   labels = "Cut: 4.11", col = "blue", pos = 4, cex = 0.8)

# [3] Average Linkage 덴드로그램
plot(hc_average,
     main = "Average Linkage",
     cex = 0.5)
abline(h = h_average_first, col = "red", lwd = 2)
abline(h = h_average_cut, col = "blue", lwd = 2)
text(x = 0, y = h_average_first, labels = "1st: 1.16", col = "red", pos = 4, cex = 0.8)
text(x = 0, y = h_average_cut,   labels = "Cut: 1.26", col = "blue", pos = 4, cex = 0.8)

Q4: Try to find the optimal k for the k means method in at least two ways.

*k-means 클러스터링이란? - 주어진 데이터를 K개의 클러스터로 나누는 비지도 학습(unsupervised learning) 알고리즘입니다. - 클러스터는 데이터들이 유사한 특성을 갖도록 구성됩니다.
- 각 데이터 포인트를 가장 가까운 중심점(centroid) 에 할당하고, 이 중심점을 반복적으로 갱신하여 군집을 형성합니다.
- 군집 내 데이터 간의 거리를 최소화하고, 군집 간 거리는 최대화하는 것이 목표입니다.

*k-means 클러스터링 과정 1. 초기 중심점 K개 무작위 생성 2. 각 데이터 → 가장 가까운 중심점에 할당 3. 중심점 갱신: 각 군집의 평균 좌표 계산 4. 수렴 조건 확인: 중심점 변화가 없을 때까지 2~3단계를 반복

*왜 최적의 K를 찾아야 할까? - 너무 적은 K: 클러스터 간의 구분이 모호 → 과소 분류, 정보를 과도하게 일반화 - 너무 많은 K: 불필요하게 세분화 → 과도한 세분화로 노이즈 포함 - 데이터 특성과 패턴을 가장 잘 설명하는 적절한 K 필요

*최적의 K를 찾는 대표 방법 방법 1: Elbow Method - 클러스터 수(K)를 늘리면 WSS (Within Sum of Squares) 감소 - 감소 폭이 급격히 줄어드는 elbow(팔꿈치) 지점을 최적 K로 간주

방법 2: Silhouette Method - 클러스터 내부 응집도와 외부 분리도를 동시에 고려 - 평균 실루엣 계수가 가장 높은 K를 선택

[방법1] Elbow Method

# [Elbow Method 설명]
# - 클러스터 수(K)에 따라 클러스터 내 제곱합 거리(WSS: Within Sum of Squares)를 계산
# - K가 커질수록 WSS는 감소하지만, 감소 폭이 급격히 꺾이는 지점(팔꿈치 elbow)이 존재함
# - 그 지점을 최적의 K로 간주

# [1단계] factoextra 패키지 설치 (최초 1회만)
# install.packages("factoextra")

# [2단계] 패키지 로드
library(factoextra)

# [3단계] 시각화 객체 생성 및 저장
elbow_plot <- fviz_nbclust(x_scaled,          # 표준화된 독립 변수 집합
                           kmeans,            # 클러스터링 알고리즘
                           method = "wss",    # WSS 기준
                           k.max = 10,        # 최대 K값 설정
                           linecolor = "steelblue") +  # 선 색상 지정
  labs(title = "Elbow Method: Optimal Number of Clusters",  # 제목
       x = "Number of Clusters (K)",                        # x축
       y = "Total Within Sum of Squares (WSS)")            # y축

# [4단계] Elbow 포인트 좌표 수동 입력 (예: K = 3에서 WSS가 약 105)
elbow_k <- 3
elbow_wss <- 1260

# [5단계] 시각화 객체에 붉은색 원형 점 추가
elbow_plot +
  annotate("point", x = elbow_k, y = elbow_wss,
           color = "red", fill = "red", size = 6, shape = 21) +
  annotate("text", x = elbow_k, y = elbow_wss + 100,
           label = paste0("WSS=", elbow_wss), color = "red", size = 4)

[방법2] Silhouette Method

# [Silhouette Method 설명]
# - 실루엣 계수는 클러스터 내부 응집도와 외부 분리도를 동시에 고려
# - 평균 실루엣 계수가 높을수록 군집화가 잘 되었음을 의미
# - 가장 높은 평균 실루엣 계수를 가지는 K를 최적의 K로 간주

# [시각화 코드]
fviz_nbclust(x_scaled,        # 표준화된 독립 변수 데이터
             kmeans,          # K-평균 클러스터링 알고리즘 사용
             method = "silhouette",  # silhouette 방법 지정
             k.max = 10,            # 최대 K 값 설정 (1~10까지 탐색)
             linecolor = "darkgreen") +  # 선 색상 지정
  labs(title = "Silhouette Method: Optimal Number of Clusters",  # 그래프 제목
       x = "Number of Clusters (K)",                             # x축 제목
       y = "Average Silhouette Width")                           # y축 제목

Q5: Conduct a k means clustering using independent variable set setting k=3 and use set.seed(1122334455) to make sure we obtain the same result. Compare the result with the dependent variable set.

5-1) K-Means Clustering 수행 및 종속 변수와 비교 (k=3, seed 고정)

# [1] 랜덤 시드 고정 (동일한 결과 재현 위해)
set.seed(1122334455)
# [2] k-means 클러스터링 수행 (클러스터 개수 K = 3)
kmeans_result <- kmeans(x_scaled, centers = 3)
# [3] 클러스터 결과 요약 출력
kmeans_result
K-means clustering with 3 clusters of sizes 51, 65, 62

Cluster means:
     Alcohol      Malic        Ash Alcalinity   Magnesium     Phenols
1  0.1644436  0.8690954  0.1863726  0.5228924 -0.07526047 -0.97657548
2 -0.9234669 -0.3929331 -0.4931257  0.1701220 -0.49032869 -0.07576891
3  0.8328826 -0.3029551  0.3636801 -0.6084749  0.57596208  0.88274724
   Flavanoids Nonflavanoid Proanthocyanins  Intensity        Hue      OD280
1 -1.21182921   0.72402116     -0.77751312  0.9388902 -1.1616353 -1.2887761
2  0.02075402  -0.03343924      0.05810161 -0.8993770  0.4606854  0.2700025
3  0.97506900  -0.56050853      0.57865427  0.1705823  0.4725622  0.7770551
     Proline
1 -0.4059428
2 -0.7517257
3  1.1220202

Clustering vector:
  [1] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
 [38] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 2 2 1 2 2 2 2 2 2 2 2 2 2 2 3
 [75] 2 2 2 2 2 2 2 2 2 1 2 2 2 2 2 2 2 2 2 2 2 3 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
[112] 2 2 2 2 2 2 2 1 2 2 3 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
[149] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

Within cluster sum of squares by cluster:
[1] 326.3543 558.6756 385.6990
 (between_SS / total_SS =  44.8 %)

Available components:

[1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss"
[6] "betweenss"    "size"         "iter"         "ifault"      

5-2) 결과값 해석 - 클러스터 1: 51개 데이터 포인트
- 클러스터 2: 65개 데이터 포인트
- 클러스터 3: 62개 데이터 포인트

# 클러스터별 중심값 출력
kmeans_result$centers
##      Alcohol      Malic        Ash Alcalinity   Magnesium     Phenols
## 1  0.1644436  0.8690954  0.1863726  0.5228924 -0.07526047 -0.97657548
## 2 -0.9234669 -0.3929331 -0.4931257  0.1701220 -0.49032869 -0.07576891
## 3  0.8328826 -0.3029551  0.3636801 -0.6084749  0.57596208  0.88274724
##    Flavanoids Nonflavanoid Proanthocyanins  Intensity        Hue      OD280
## 1 -1.21182921   0.72402116     -0.77751312  0.9388902 -1.1616353 -1.2887761
## 2  0.02075402  -0.03343924      0.05810161 -0.8993770  0.4606854  0.2700025
## 3  0.97506900  -0.56050853      0.57865427  0.1705823  0.4725622  0.7770551
##      Proline
## 1 -0.4059428
## 2 -0.7517257
## 3  1.1220202

5-2) 클러스터 내 제곱합(WSS) 및 클러스터 간 제곱합(BSS) 확인

# [5] 클러스터 내 제곱합 (Within Cluster Sum of Squares)
kmeans_result$withinss
## [1] 326.3543 558.6756 385.6990
# [6] 클러스터 간 제곱합 비율 계산
bss_ratio <- round(kmeans_result$betweenss / kmeans_result$totss * 100, 1)
bss_ratio
## [1] 44.8

5-3) 종속 변수(y)와의 비교 (Confusion Matrix)

# [7] 클러스터 결과와 실제 클래스 비교
# kmeans_result$cluster와 y의 길이를 동일하게 맞춤
y_vec <- as.vector(unlist(y))  # y를 벡터로 변환
y_vec <- y_vec[1:length(kmeans_result$cluster)]  # 길이 맞추기

# Confusion Matrix 계산
conf_mat <- table(kmeans_result$cluster, y_vec)
conf_mat
##    y_vec
##      A  B  C
##   1  3 48  0
##   2 65  0  0
##   3  3  0 59

Q6: Try to convert the dependent variable to integer and calculate accuracy.

# [7] 종속변수 y를 정수형 벡터로 변환
y_int <- as.integer(as.factor(unlist(y)))   # 데이터프레임 → 벡터 → factor → integer

# [8] Confusion Matrix 생성 및 정확도 계산
conf_mat <- table(kmeans_result$cluster, y_int)  # 군집 결과 vs 실제 클래스
conf_mat
##    y_int
##      1  2  3
##   1  3 48  0
##   2 65  0  0
##   3  3  0 59
correct <- sum(diag(conf_mat))             # 올바르게 분류된 데이터 수
total <- sum(conf_mat)                     # 전체 데이터 수
accuracy <- round(correct / total * 100, 2)  # 정확도(소수 둘째 자리까지)
accuracy
## [1] 34.83
head(y_int)
## [1] 3 3 3 3 3 3
클러스터 실제 Class A 실제 Class B 실제 Class C 주요 클래스 추정
1 3 48 0 Class B
2 65 0 0 Class A
3 0 3 59 Class C

정확도: 96.63%