La segmentación o clusters es un conjunto de técnicas cuyo propósito es formar grupos a partir de un conjunto de elementos.
#install.packages("cluster")
library(cluster)
#install.packages("ggplot2")
library(ggplot2)
#install.packages("data.table")
library(data.table)
#install.packages("factoextra")
library(factoextra)
## Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa
df <- data.frame(x= c(2,2,8,5,7,6,1,4), y= c(10,5,4,8,5,4,2,9))
Normalmente se arranca con 3-4 grupos
grupos <- 3
segmentos <- kmeans(df, grupos)
segmentos
## K-means clustering with 3 clusters of sizes 3, 3, 2
##
## Cluster means:
## x y
## 1 7.000000 4.333333
## 2 3.666667 9.000000
## 3 1.500000 3.500000
##
## Clustering vector:
## [1] 2 3 1 2 1 1 3 2
##
## Within cluster sum of squares by cluster:
## [1] 2.666667 6.666667 5.000000
## (between_SS / total_SS = 85.8 %)
##
## Available components:
##
## [1] "cluster" "centers" "totss" "withinss" "tot.withinss"
## [6] "betweenss" "size" "iter" "ifault"
summary(segmentos)
## Length Class Mode
## cluster 8 -none- numeric
## centers 6 -none- numeric
## totss 1 -none- numeric
## withinss 3 -none- numeric
## tot.withinss 1 -none- numeric
## betweenss 1 -none- numeric
## size 3 -none- numeric
## iter 1 -none- numeric
## ifault 1 -none- numeric
asignación <- cbind(cluster = segmentos$cluster, df)
asignación
## cluster x y
## 1 2 2 10
## 2 3 2 5
## 3 1 8 4
## 4 2 5 8
## 5 1 7 5
## 6 1 6 4
## 7 3 1 2
## 8 2 4 9
asignación$cluster <- as.factor(asignación$cluster)
summary(asignación)
## cluster x y
## 1:3 Min. :1.000 Min. : 2.000
## 2:3 1st Qu.:2.000 1st Qu.: 4.000
## 3:2 Median :4.500 Median : 5.000
## Mean :4.375 Mean : 5.875
## 3rd Qu.:6.250 3rd Qu.: 8.250
## Max. :8.000 Max. :10.000
fviz_cluster(segmentos, data = df)
La cantidad óptima de grupos corresponde al punto más alto de la siguiente gráfica:
set.seed(123)
optimizacion <- clusGap(df, FUN=kmeans, nstart=1, K.max = 7)
plot(optimizacion, xlab = "Número de clusters k")
La segmentación o clusters es un algoritmo útil para las empresas que desean clasificar a sus clientes y dirigir campañas de marketing más enfocadas y especializadas.