본문 바로가기
데이터분석/R

[현장에서 바로 써먹는...] 군집분석

by 버섯도리 2022. 4. 9.

> ## Chapter 6-3. 효과적인 사육을 위해 사육환경을 분리해보자 (군집 알고리즘)

> # K-means Clustering

> cl <- read.csv("ch6-3.csv", header = TRUE)  # 데이터 셋 불러오기
> str(cl)  # 데이터 셋 형태 확인
'data.frame': 100 obs. of  3 variables:
 $ breeds: chr  "a" "a" "a" "a" ...
 $ weight: int  2765 2843 2678 2595 2734 2616 2605 2838 2900 2415 ...
 $ food  : int  217 235 207 204 226 197 216 219 237 178 ...
> cl$breeds <- as.factor(cl$breeds)
> summary(cl)
 breeds      weight          food    
 a:100   Min.   :2403   Min.   :178  
         1st Qu.:2551   1st Qu.:197  
         Median :2694   Median :214  
         Mean   :2696   Mean   :213  
         3rd Qu.:2834   3rd Qu.:228  
         Max.   :2999   Max.   :249  

plot(cl$food, cl$weight)  # 산점도, x축 food, y축 weight


> cl_kmc <- kmeans(cl[,2:3], 3)  # k-means 군집 실시, k=3
> cl_kmc
K-means clustering with 3 clusters of sizes 37, 34, 29

Cluster means:
    weight     food
1 2503.973 193.7568
2 2718.765 215.7353
3 2913.414 234.2069

Clustering vector:
  [1] 2 3 2 1 2 2 1 3 3 1 1 3 1 2 1 2 1 3 1 3 3 2 3 2 3 2 1 2 3 1 3 1 1 2 3 3 1 2 3 1 3 3 1 1 1 1 2 2 3 3 1 1 2 2 2 2 2 2 3
 [60] 2 1 1 2 3 3 1 3 3 3 1 1 2 2 1 3 2 1 3 2 1 1 3 1 1 1 1 2 2 2 2 2 1 3 2 2 2 1 1 1 3

Within cluster sum of squares by cluster:
[1] 160475.8 115200.7 119763.8
 (between_SS / total_SS =  87.5 %)

Available components:

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

> cl$cluster <- cl_kmc$cluster  # 군집결과 기존 데이터 셋에 입력
> head(cl)  # 데이터 확인
  breeds weight food cluster
1      a   2765  217       2
2      a   2843  235       3
3      a   2678  207       2
4      a   2595  204       1
5      a   2734  226       2
6      a   2616  197       2

> # 산점도를 이용해 군집결과 확인, cluster에 따라 3가지 색상 부여
plot(cl$food, cl$weight, col = c("red", "blue", "green")[cl$cluster])


> library(cluster)

> # clusplot 함수를 이용해 더 보기 쉽게 군집 표현, col.p 옵션을 통해 군집에 따른 색상지정
clusplot(cl[,2:3], cl$cluster, col.p = cl$cluster)

 

 

 

 

 

 

출처 : 현장에서 바로 써먹는 데이터 분석 with R