d <- read.csv('https://stats.dip.jp/01_ds/data/Mall_Customers.csv')
colnames(d) <- c('id', 'gender', 'age', 'income', 'score')

library(DT)
datatable(d, options = list(pageLength = 5))
NGROUPS <- 5
COL <- rainbow(NGROUPS)

matplot(x = d$income, y = d$score, pch = 16, type = 'p', col = COL[1])
grid()

km <- kmeans(d[,c('income', 'score')], centers = NGROUPS, nstart = 25)

c <- vector('list', NGROUPS)

name.group <- rep(NA, NGROUPS)

matplot(x = d$income, y = d$score, type = 'n', pch = 1)
grid()

for (i in 1:NGROUPS)
{
  c[[i]] <- d[km$cluster == i, ]
  
  matpoints(x = c[[i]]$income,
            y = c[[i]]$score,
            pch = 16,
            col = COL[i])
  
  name.group[i] <- names(which.max(table(c[[i]]$score)))
}

legend('topright', pch = 16, col = COL[1:NGROUPS], legend = paste0('Group', 1:NGROUPS))

library(factoextra)
##  要求されたパッケージ ggplot2 をロード中です
## Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa

fviz_cluster(km, data = d[, c('income','score')])

library(cluster)
pm <- pam(d[, c('income','score')], k = NGROUPS)
plot(pm)

cl <- clara(d[, c('income','score')], k = NGROUPS, pamLike = T, samples = 1)
plot(cl)

cl2 <- clara(d[, c('income','score')], k = NGROUPS, pamLike = F, samples = 50)
plot(cl2)