#Instalar paquetes
library("cluster")
library("ggplot2")
library("data.table")
library("factoextra")
#Obtener los datos
df <- data.frame(x=c(2,2,8,5,7,6,1,4),y=c(10,5,4,8,5,4,2,9))
#Cantidad de grupos
grupos <- 3
#Generar segmentos
segmentos <- kmeans(df,grupos)
segmentos
## K-means clustering with 3 clusters of sizes 3, 2, 3
##
## Cluster means:
## x y
## 1 3.666667 9.000000
## 2 1.500000 3.500000
## 3 7.000000 4.333333
##
## Clustering vector:
## [1] 1 2 3 1 3 3 2 1
##
## Within cluster sum of squares by cluster:
## [1] 6.666667 5.000000 2.666667
## (between_SS / total_SS = 85.8 %)
##
## Available components:
##
## [1] "cluster" "centers" "totss" "withinss" "tot.withinss"
## [6] "betweenss" "size" "iter" "ifault"
#Asignar grupo
asignacion <- cbind(df,cluste = segmentos$cluster)
asignacion
## x y cluste
## 1 2 10 1
## 2 2 5 2
## 3 8 4 3
## 4 5 8 1
## 5 7 5 3
## 6 6 4 3
## 7 1 2 2
## 8 4 9 1
#Graficar cluster
fviz_cluster(segmentos, data=df)
#Optimizar
set.seed(123)
optimizacion <- clusGap(df,FUN=kmeans, nstart=1,K.max=7)
plot(optimizacion, xlab= "Número de clusters k")
#Conclusion El clustering es un método que sirve para segmentar conjuntos de datos en base a una característica.