# 讀取數據
zscoredFile <- read.csv('D:/Rdata/zscoredFile.csv')
set.seed(123) # 設置隨機種子
result <- kmeans(zscoredFile, 5) # 建立模型,聚類中心爲5
round(result$centers, 3) # 查看聚類中心
table(result$cluster) # 統計不同類別樣本的數目
# 畫出客戶羣特徵分析雷達圖
library(fmsb)
max <- apply(result$centers, 2, max)
min <- apply(result$centers, 2, min)
df <- data.frame(rbind(max, min, result$centers))
radarchart(df = df, seg =5, plty = c(1:5), vlcex = 1, plwd = 2)
# 給雷達圖加圖例
L <- 1
for(i in 1:5){
legend(1.3, L, legend = paste("客戶羣", i), lty = i, lwd = 3, col = i, bty = "n")
L <- L - 0.2
}
#Legend函數前兩個參數代表圖例位置座標,這裏循環輸出是爲了防止圖例覆蓋在同一位置,故預先設定好第一個圖例位置,再作相應調整已確定其他圖例位置。
部分運行結果:
雷達圖: