非階層的クラスタリング

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)

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])
  
}

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