library(readr)
# file.choose()
spotify <- read_csv("/Users/constantinomilletxacur/Desktop/Concentracion/Most Streamed Spotify Songs 2024.csv")
## Warning: One or more parsing issues, call `problems()` on your data frame for details,
## e.g.:
## dat <- vroom(...)
## problems(dat)
## Rows: 4615 Columns: 1
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (1): Most Streamed Spotify Songs 2024
##
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# La segmentación o clusters es un conjunto
# de técnicas cuyo propósito es formar
# grupos a partir de un conjunto de elementos.
# Paso 1. Instalar paquetes y llamar librerías
library(cluster)
library(ggplot2)
library(data.table)
library(factoextra)
## Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa
# Paso 2. 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))
# Paso 3. Cantidad de grupos
grupos <- 3
# Paso 4. Generar los segmentos
segmentos <- kmeans(df,4)
segmentos
## K-means clustering with 4 clusters of sizes 3, 1, 2, 2
##
## Cluster means:
## x y
## 1 7.0 4.333333
## 2 2.0 10.000000
## 3 1.5 3.500000
## 4 4.5 8.500000
##
## Clustering vector:
## [1] 2 3 1 4 1 1 3 4
##
## Within cluster sum of squares by cluster:
## [1] 2.666667 0.000000 5.000000 1.000000
## (between_SS / total_SS = 91.4 %)
##
## Available components:
##
## [1] "cluster" "centers" "totss" "withinss" "tot.withinss"
## [6] "betweenss" "size" "iter" "ifault"
# Paso 5. Asignar el grupo al que pertenece cada observación
asignacion <- cbind(df, cluster = segmentos$cluster)
asignacion
## x y cluster
## 1 2 10 2
## 2 2 5 3
## 3 8 4 1
## 4 5 8 4
## 5 7 5 1
## 6 6 4 1
## 7 1 2 3
## 8 4 9 4
# Paso 6. Graficar los clusters
fviz_cluster(segmentos, data=df)
# Paso 7. Optimizar la cantidad de grupos
# 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")
install.packages(“cluster”) library(cluster) install.packages(“ggplot2”) library(ggplot2) install.packages(“data.table”) library(data.table) install.packages(“factoextra”) library(factoextra)
df <- data.frame(x=c(2,2,8,5,7,6,1,4), y=c(10,5,4,8,5,4,2,9))
grupos <- 3
segmentos <- kmeans(df,4) segmentos # Paso 5. Asignar el grupo al que pertenece cada observación asignacion <- cbind(df, cluster = segmentos$cluster) asignacion
fviz_cluster(segmentos, data=df)
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 sus clientes y dirigir campañas de marketing más enfocadas y especializadas.