library(foreign)
library(dplyr) # data manipulation
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(ggplot2) # data visualization
library(psych) # functions for multivariate analysis
##
## Attaching package: 'psych'
## The following objects are masked from 'package:ggplot2':
##
## %+%, alpha
library(corrplot) # correlation plots
## corrplot 0.92 loaded
library(jtools) # presentation of regression analysis
library(lmtest) # diagnostic checks - linear regression analysis
## Loading required package: zoo
##
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
##
## as.Date, as.Date.numeric
library(car) # diagnostic checks - linear regression analysis
## Loading required package: carData
##
## Attaching package: 'car'
## The following object is masked from 'package:psych':
##
## logit
## The following object is masked from 'package:dplyr':
##
## recode
library(factoextra) # provides functions to extract and visualize the output of exploratory multivariate data analyses
## Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa
library(ggfortify) # data visualization tools for statistical analysis results
summary(rh)
## nombre_completo fecha_nac genero fecha_alta
## Length:238 Length:238 Length:238 Length:238
## Class :character Class :character Class :character Class :character
## Mode :character Mode :character Mode :character Mode :character
##
##
##
##
## mot_baja permanencia baja puesto
## Length:238 Min. : 0.00 Length:238 Length:238
## Class :character 1st Qu.: 9.00 Class :character Class :character
## Mode :character Median : 19.00 Mode :character Mode :character
## Mean : 79.71
## 3rd Qu.: 49.00
## Max. :1966.00
## NA's :25
## departamento sal_diario_imss colonia CP
## Length:238 Min. :144.4 Length:238 Min. : 0
## Class :character 1st Qu.:180.7 Class :character 1st Qu.:66645
## Mode :character Median :180.7 Mode :character Median :66646
## Mean :178.0 Mean :64816
## 3rd Qu.:180.7 3rd Qu.:66649
## Max. :500.0 Max. :99999
## NA's :3
## municipio estado estado_civil edad
## Length:238 Length:238 Length:238 Length:238
## Class :character Class :character Class :character Class :character
## Mode :character Mode :character Mode :character Mode :character
##
##
##
##
Remplazar los NA en “permanencia” y “edad” por la media del puesto
Observar cuantos NA´s tenemos por columna
rh_2 <- rh_1
colSums(is.na(rh_2))
## nombre_completo fecha_nac genero fecha_alta mot_baja
## 0 1 0 1 25
## permanencia baja puesto departamento sal_diario_imss
## 3 15 0 0 0
## colonia CP municipio estado estado_civil
## 0 3 0 0 0
## edad
## 0
class(rh_2$permanencia)
## [1] "numeric"
class(rh_2$baja)
## [1] "character"
class(rh_2$edad)
## [1] "character"
class(rh_2$sal_diario_imss)
## [1] "numeric"
rh_2$baja <- as.Date(rh_2$baja)
rh_2$edad <- as.integer(rh_2$edad)
## Warning: NAs introduced by coercion
rh_2$permanencia <- as.integer(rh_2$permanencia)
Agregar columna de mes de baja
rh_3 <- rh_2
rh_3$mes_baja <- as.numeric(format(rh_3$baja, '%m'))
rh_3
## # A tibble: 238 × 17
## # Groups: puesto [22]
## nombre_com…¹ fecha…² genero fecha…³ mot_b…⁴ perma…⁵ baja puesto depar…⁶
## <chr> <chr> <chr> <chr> <chr> <int> <date> <chr> <chr>
## 1 MARIO VALDE… 1990-0… MASCU… 2020-0… RENUNC… 628 2021-11-27 DISE�O "ADMIN…
## 2 ISABEL BARR… 1986-0… FEMEN… 2021-1… RENUNC… 60 2022-01-08 AYUDA… "PRODU…
## 3 MARIA ELIZA… 1999-0… FEMEN… 2021-1… RENUNC… 59 2022-01-08 AYUDA… "STABI…
## 4 ALONDRA ABI… 2001-0… FEMEN… 2021-1… RENUNC… 59 2022-01-08 AYUDA… "CELDA…
## 5 ERIKA ROSAL… 1993-0… FEMEN… 2021-1… RENUNC… 51 2022-01-08 AYUDA… ""
## 6 GUADALUPE S… 1976-1… FEMEN… 2021-1… BAJA P… 37 2022-01-08 AYUDA… ""
## 7 YOANA CRIST… 1993-0… FEMEN… 2021-1… BAJA P… 37 2022-01-08 AYUDA… ""
## 8 CESAR ANTON… 1991-0… MASCU… 2021-1… BAJA P… 31 2022-01-08 AYUDA… ""
## 9 ROBERTO SAE… 1972-0… MASCU… 2021-1… BAJA P… 18 2022-01-08 AYUDA… ""
## 10 JAIME DANIE… 2003-0… MASCU… 2021-0… RENUNC… 224 2022-01-10 AYUDA… "MATER…
## # … with 228 more rows, 8 more variables: sal_diario_imss <dbl>, colonia <chr>,
## # CP <int>, municipio <chr>, estado <chr>, estado_civil <chr>, edad <int>,
## # mes_baja <dbl>, and abbreviated variable names ¹nombre_completo,
## # ²fecha_nac, ³fecha_alta, ⁴mot_baja, ⁵permanencia, ⁶departamento
class(rh_3$permanencia)
## [1] "integer"
class(rh_3$baja)
## [1] "Date"
class(rh_3$edad)
## [1] "integer"
class(rh_3$sal_diario_imss)
## [1] "numeric"
class(rh_3$mes_baja)
## [1] "numeric"
summary(rh_3)
## nombre_completo fecha_nac genero fecha_alta
## Length:238 Length:238 Length:238 Length:238
## Class :character Class :character Class :character Class :character
## Mode :character Mode :character Mode :character Mode :character
##
##
##
##
## mot_baja permanencia baja puesto
## Length:238 Min. : 0.00 Min. :2021-11-27 Length:238
## Class :character 1st Qu.: 9.00 1st Qu.:2022-02-25 Class :character
## Mode :character Median : 21.00 Median :2022-04-29 Mode :character
## Mean : 77.96 Mean :2022-04-29
## 3rd Qu.: 60.00 3rd Qu.:2022-06-29
## Max. :1966.00 Max. :2022-08-25
## NA's :3 NA's :15
## departamento sal_diario_imss colonia CP
## Length:238 Min. :144.4 Length:238 Min. : 0
## Class :character 1st Qu.:180.7 Class :character 1st Qu.:66645
## Mode :character Median :180.7 Mode :character Median :66646
## Mean :178.0 Mean :64816
## 3rd Qu.:180.7 3rd Qu.:66649
## Max. :500.0 Max. :99999
## NA's :3
## municipio estado estado_civil edad
## Length:238 Length:238 Length:238 Min. : 0.00
## Class :character Class :character Class :character 1st Qu.:23.00
## Mode :character Mode :character Mode :character Median :28.00
## Mean :30.39
## 3rd Qu.:37.00
## Max. :61.00
## NA's :1
## mes_baja
## Min. : 1.000
## 1st Qu.: 2.000
## Median : 4.000
## Mean : 4.475
## 3rd Qu.: 6.000
## Max. :11.000
## NA's :15
Reemplazar los NA por el mes 7
rh_4 <- rh_3
rh_4$mes_baja <- replace(rh_4$mes_baja, is.na(rh_4$mes_baja), 7)
Variables que vamos a analizar en el análisis k-means
rh_alt<-rh_4 %>% select(sal_diario_imss, edad, permanencia, mes_baja)
## Adding missing grouping variables: `puesto`
rh_alt
## # A tibble: 238 × 5
## # Groups: puesto [22]
## puesto sal_diario_imss edad permanencia mes_baja
## <chr> <dbl> <int> <int> <dbl>
## 1 DISE�O 500 32 628 11
## 2 AYUDANTE GENERAL 152. 36 60 1
## 3 AYUDANTE GENERAL 152. 23 59 1
## 4 AYUDANTE GENERAL 152. 21 59 1
## 5 AYUDANTE GENERAL 152. 29 51 1
## 6 AYUDANTE GENERAL 152. 46 37 1
## 7 AYUDANTE GENERAL 152. 29 37 1
## 8 AYUDANTE GENERAL 152. 31 31 1
## 9 AYUDANTE GENERAL 152. 50 18 1
## 10 AYUDANTE GENERAL 177. 19 224 1
## # … with 228 more rows
Eliminar NA´s
rh_alt<-rh_alt[-c(196, 197,200),] #
summary(rh_alt) # no missing values
## puesto sal_diario_imss edad permanencia
## Length:235 Min. :144.4 Min. : 0.00 Min. : 0.00
## Class :character 1st Qu.:180.7 1st Qu.:23.00 1st Qu.: 9.00
## Mode :character Median :180.7 Median :28.00 Median : 21.00
## Mean :178.0 Mean :30.43 Mean : 77.96
## 3rd Qu.:180.7 3rd Qu.:37.00 3rd Qu.: 60.00
## Max. :500.0 Max. :61.00 Max. :1966.00
## mes_baja
## Min. : 1.000
## 1st Qu.: 3.000
## Median : 5.000
## Mean : 4.604
## 3rd Qu.: 7.000
## Max. :11.000
En equipo describir con sus propias palabras cómo los siguientes conceptos contribuyen a la identificación de clusters usando analítica de datos:
El objetivo del K-Means Clustering es dividir el conjunto de datos en
subpoblaciones de objetos que son similares y pertenecen dentro de un
grupo específico acorde a sus características.
Además este método es probablemente el más utilizado en la ciencia de
datos.
Ejemplos para aplicar K-Means: - Segmentación de
clientes.
- Comunidades de redes sociales
- Geo estadística
La clusterización es un algoritmo de aprendizaje no
supervisado.
El algoritmo de aprendizaje no supervisado sirve para explorar,
describir y resumir datos, así como también a descubrir patrones y
relaciones, pero sin existir una categorización o etiquetado de datos
previo, por lo tanto, se agrupará según las características y
similitudes.
Se emplea para medir la disimilitud (Falta de semejanza o de
parecido entre dos o más cosas) y es la más utilizada al momento de
realizar K-Means clustering.
Dicha distancia mide una línea recta entre el punto de consulta y el
otro punto que se mide.
#Normalizar las variables
rh_alt1 <- rh_alt
rh_alt1 <- subset(rh_alt1, permanencia>0 & permanencia<79)
rh_alt1 <- subset(rh_alt1, edad>24 & edad<38)
rh_permanencia<-scale(rh_alt1[3:4])
summary(rh_permanencia)
## edad permanencia
## Min. :-1.4589 Min. :-1.0086
## 1st Qu.:-0.9356 1st Qu.:-0.7421
## Median :-0.1505 Median :-0.3598
## Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.8963 3rd Qu.: 0.3470
## Max. : 1.6814 Max. : 2.5138
fviz_nbclust(rh_permanencia, kmeans, method="wss")+ # wss method considers total within sum of square
geom_vline(xintercept=4, linetype=2)+ # optimal number of clusters is computed with the default method = "euclidean"
labs(subtitle = "Elbow method")
## Registered S3 methods overwritten by 'broom':
## method from
## tidy.glht jtools
## tidy.summary.glht jtools
# visualize the clusters' information. Briefly, you can detect how each dataset's observation corresponds to a specific cluster.
permanencia_cluster1<-kmeans(rh_permanencia,4)
permanencia_cluster1
## K-means clustering with 4 clusters of sizes 26, 9, 37, 8
##
## Cluster means:
## edad permanencia
## 1 0.9667615 -0.6075563
## 2 0.9544596 1.6177287
## 3 -0.7799570 -0.3672901
## 4 -0.6084407 1.8533297
##
## Clustering vector:
## [1] 2 4 3 3 2 3 3 1 1 1 3 3 3 3 3 3 3 1 3 1 4 4 1 3 3 3 1 3 3 1 1 3 1 1 3 3 1 3
## [39] 1 3 1 1 3 1 1 3 3 1 1 3 3 3 3 3 3 1 2 2 2 2 4 2 1 2 3 4 4 2 4 3 1 1 3 1 1 4
## [77] 3 3 3 1
##
## Within cluster sum of squares by cluster:
## [1] 10.327682 3.140087 16.382860 4.559511
## (between_SS / total_SS = 78.2 %)
##
## Available components:
##
## [1] "cluster" "centers" "totss" "withinss" "tot.withinss"
## [6] "betweenss" "size" "iter" "ifault"
# visualize clustering results
fviz_cluster(permanencia_cluster1,data=rh_permanencia)
#lets add the estimated clusters’ information to the original dataset so we can interpret the results
rh_alt_tabla<-rh_alt1
rh_alt_tabla$Clusters<-permanencia_cluster1$cluster
#lets create a dataset so we can identify some characteristics of “permanencia” by cluster
rh_alt_tabla2<-rh_alt_tabla %>% group_by(Clusters) %>% summarise(permanencia=max(permanencia)) %>% arrange(desc(permanencia))
#group the clusters by name
rh_alt_tabla$Cluster_Names<-factor(rh_alt_tabla$Clusters,levels = c(1,2,3,4),
labels=c("Antigüedad Baja", "Antigüedad Alta", "Antigüedad Moderada", "Antigüedad Avanzada"))
#group the clusters by cluster names and Summarize the Columns
rh_alt_tabla3 <- rh_alt_tabla %>% group_by(Cluster_Names) %>% summarize(permanencia_años=max(permanencia),
edad=mean(edad),
Count=n())
clusters<-as.data.frame(rh_alt_tabla3)
clusters
## Cluster_Names permanencia_años edad Count
## 1 Antigüedad Baja 29 34.26923 26
## 2 Antigüedad Alta 60 34.22222 9
## 3 Antigüedad Moderada 37 27.59459 37
## 4 Antigüedad Avanzada 77 28.25000 8
#lets plot the number of data observations by clusters names
ggplot(rh_alt_tabla3,aes(x=reorder(Cluster_Names,Count),y=Count,fill=Cluster_Names)) +
geom_bar(stat="identity")
summary(rh_alt)
## puesto sal_diario_imss edad permanencia
## Length:235 Min. :144.4 Min. : 0.00 Min. : 0.00
## Class :character 1st Qu.:180.7 1st Qu.:23.00 1st Qu.: 9.00
## Mode :character Median :180.7 Median :28.00 Median : 21.00
## Mean :178.0 Mean :30.43 Mean : 77.96
## 3rd Qu.:180.7 3rd Qu.:37.00 3rd Qu.: 60.00
## Max. :500.0 Max. :61.00 Max. :1966.00
## mes_baja
## Min. : 1.000
## 1st Qu.: 3.000
## Median : 5.000
## Mean : 4.604
## 3rd Qu.: 7.000
## Max. :11.000
rh_salario<-scale(rh_alt2[4:5])
summary(rh_salario)
## sal_diario_imss permanencia
## Min. :-2.8567 Min. :-1.1201
## 1st Qu.: 0.3499 1st Qu.:-0.7992
## Median : 0.3499 Median :-0.2643
## Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.3499 3rd Qu.: 0.7518
## Max. : 0.6808 Max. : 2.5168
fviz_nbclust(rh_salario, kmeans, method="wss")+ # wss method considers total within sum of square
geom_vline(xintercept=4, linetype=2)+ # optimal number of clusters is computed with the default method = "euclidean"
labs(subtitle = "Elbow method")
# visualize the clusters' information. Briefly, you can detect how each dataset's observation corresponds to a specific cluster.
salario_cluster1<-kmeans(rh_salario,4)
salario_cluster1
## K-means clustering with 4 clusters of sizes 15, 30, 30, 64
##
## Cluster means:
## sal_diario_imss permanencia
## 1 -2.8567440 0.47016757
## 2 0.3281298 0.01199211
## 3 0.3353366 1.54875184
## 4 0.3585495 -0.84179425
##
## Clustering vector:
## [1] 1 1 1 1 1 1 1 1 1 1 2 2 1 1 1 1 1 4 4 4 4 4 4 4 3 4 4 2 2 4 4 2 2 2 4 4 4
## [38] 2 2 3 2 4 3 3 3 2 4 3 3 3 3 2 4 4 4 2 4 4 4 4 4 4 4 2 2 4 4 4 4 4 3 2 4 4
## [75] 4 4 2 2 4 4 4 2 4 4 4 4 2 4 4 2 4 4 4 4 4 4 4 4 4 2 2 3 3 3 3 3 3 3 4 3 3
## [112] 4 3 3 4 3 3 3 3 3 3 3 3 4 4 4 4 4 3 2 2 2 4 2 4 4 2 2 2
##
## Within cluster sum of squares by cluster:
## [1] 8.309523 2.567639 4.603043 2.643046
## (between_SS / total_SS = 93.4 %)
##
## Available components:
##
## [1] "cluster" "centers" "totss" "withinss" "tot.withinss"
## [6] "betweenss" "size" "iter" "ifault"
# visualize clustering results
fviz_cluster(salario_cluster1,data=rh_salario)
#lets add the estimated clusters’ information to the original dataset so we can interpret the results
rh_alt2_tabla<-rh_alt2
rh_alt2_tabla$Clusters<-salario_cluster1$cluster
#lets create a dataset so we can identify some characteristics of “permanencia” by cluster
rh_alt2_tabla2<-rh_alt2_tabla %>% group_by(Clusters) %>% summarise(permanencia=max(permanencia)) %>% arrange(desc(permanencia))
#group the clusters by name
rh_alt2_tabla$Cluster_Names<-factor(rh_alt2_tabla$Clusters,levels = c(1,2,3,4),
labels=c("Antigüedad Alta", "Antigüedad Moderada", "Antigüedad Avanzada", "Antigüedad Baja"))
#group the clusters by cluster names and Summarize the Columns
rh_alt2_tabla3 <- rh_alt2_tabla %>% group_by(Cluster_Names) %>% summarize(permanencia_dias=max(permanencia),
sal_diario_imss=mean(sal_diario_imss),
Count=n())
clusters<-as.data.frame(rh_alt2_tabla3)
clusters
## Cluster_Names permanencia_dias sal_diario_imss Count
## 1 Antigüedad Alta 60 151.6100 15
## 2 Antigüedad Moderada 41 180.4827 30
## 3 Antigüedad Avanzada 77 180.5480 30
## 4 Antigüedad Baja 22 180.7584 64
#lets plot the number of data observations by clusters names
ggplot(rh_alt2_tabla3,aes(x=reorder(Cluster_Names,Count),y=Count,fill=Cluster_Names)) +
geom_bar(stat="identity")
summary(rh_alt)
## puesto sal_diario_imss edad permanencia
## Length:235 Min. :144.4 Min. : 0.00 Min. : 0.00
## Class :character 1st Qu.:180.7 1st Qu.:23.00 1st Qu.: 9.00
## Mode :character Median :180.7 Median :28.00 Median : 21.00
## Mean :178.0 Mean :30.43 Mean : 77.96
## 3rd Qu.:180.7 3rd Qu.:37.00 3rd Qu.: 60.00
## Max. :500.0 Max. :61.00 Max. :1966.00
## mes_baja
## Min. : 1.000
## 1st Qu.: 3.000
## Median : 5.000
## Mean : 4.604
## 3rd Qu.: 7.000
## Max. :11.000
rh_mesbaja<-scale(rh_alt3[2:3])
summary(rh_mesbaja)
## mes_baja edad
## Min. :-1.68512 Min. :-1.2349
## 1st Qu.:-0.80017 1st Qu.:-0.8895
## Median : 0.08479 Median :-0.3137
## Mean : 0.00000 Mean : 0.0000
## 3rd Qu.: 0.96974 3rd Qu.: 0.7226
## Max. : 2.73964 Max. : 3.0256
fviz_nbclust(rh_mesbaja, kmeans, method="wss")+ # wss method considers total within sum of square
geom_vline(xintercept=4, linetype=2)+ # optimal number of clusters is computed with the default method = "euclidean"
labs(subtitle = "Elbow method")
# visualize the clusters' information. Briefly, you can detect how each dataset's observation corresponds to a specific cluster.
mesbaja_cluster1<-kmeans(rh_mesbaja,4)
mesbaja_cluster1
## K-means clustering with 4 clusters of sizes 66, 24, 49, 28
##
## Cluster means:
## mes_baja edad
## 1 0.7887252 -0.4724990
## 2 -0.8923490 1.1736210
## 3 -0.9897991 -0.7085313
## 4 0.6378810 1.3477166
##
## Clustering vector:
## [1] 1 3 3 2 3 3 2 3 3 3 3 2 3 2 3 3 3 3 3 3 3 3 3 3 3 2 2 2 2 3 2 3 2 3 3 2 3
## [38] 3 2 2 3 3 2 3 3 3 2 2 3 3 2 3 3 2 3 2 2 3 3 2 3 3 3 3 2 3 3 3 2 3 3 1 1 1
## [75] 3 2 3 1 4 4 4 1 1 1 1 1 1 4 1 1 4 1 1 1 4 1 4 1 1 4 4 4 1 1 1 1 1 1 1 4 4
## [112] 1 1 4 4 4 4 1 4 1 1 1 4 1 4 1 4 1 4 4 1 1 1 1 4 1 1 1 1 1 1 1 1 1 1 1 1 4
## [149] 1 4 1 1 1 1 1 1 1 4 1 1 1 1 1 4 1 4 1
##
## Within cluster sum of squares by cluster:
## [1] 35.77270 15.78750 23.85718 13.76712
## (between_SS / total_SS = 73.1 %)
##
## Available components:
##
## [1] "cluster" "centers" "totss" "withinss" "tot.withinss"
## [6] "betweenss" "size" "iter" "ifault"
# visualize clustering results
fviz_cluster(mesbaja_cluster1,data=rh_mesbaja)
#lets add the estimated clusters’ information to the original dataset so we can interpret the results
rh_alt3_tabla<-rh_alt3
rh_alt3_tabla$Clusters<-mesbaja_cluster1$cluster
#lets create a dataset so we can identify some characteristics of “permanencia” by cluster
rh_alt3_tabla2<-rh_alt3_tabla %>% group_by(Clusters) %>% summarise(edad=max(edad)) %>% arrange(desc(edad))
#group the clusters by name
rh_alt3_tabla$Cluster_Names<-factor(rh_alt3_tabla$Clusters,levels = c(1,2,3,4),
labels=c("Adulta", "Jubilación", "Joven Adulta", "Avanzada"))
#group the clusters by cluster names and Summarize the Columns
rh_alt3_tabla3 <- rh_alt3_tabla %>% group_by(Cluster_Names) %>% summarize(edad=max(edad),
mes_baja=mean(mes_baja),
Count=n())
clusters<-as.data.frame(rh_alt3_tabla3)
clusters
## Cluster_Names edad mes_baja Count
## 1 Adulta 38 6.590909 66
## 2 Jubilación 61 2.791667 24
## 3 Joven Adulta 36 2.571429 49
## 4 Avanzada 57 6.250000 28
#lets plot the number of data observations by clusters names
ggplot(rh_alt3_tabla3,aes(x=reorder(Cluster_Names,Count),y=Count,fill=Cluster_Names)) +
geom_bar(stat="identity")
Hallazgo 1. Las personas con menos permanencia en la empresa son la principal causa de la gran catidad de bajas.
Hallazgo 2. El salario no es factor que influye en la permanencia de una persona dentro de la empresa. Se encontró que las personas que tienen el mismo salario tienen una permanencia variada al igual de los que ganan menos.
Hallazgo 3 De acuerdo al salario diario con la permanencia es contante, sin importar cuánto tiempo lleves en la empresa el salario permanece en 180 pesos diarios.
Hallazgo 4 Del grupo de edad adulta y edad avanzada el mes donde obtuvieron más bajas fue en el mes de agosto.
Hallazgo 5 Del grupo de jubilación y joven adulta el mes donde obtuvieron más bajas fue en el mes de febrero.
Miniak-Górecka, A., Podlaski, K., & Gwizdałła, T. (2022). Using K-Means Clustering in Python with Periodic Boundary Conditions. Symmetry (20738994), 14(6), N.PAG. https://0-doi-org.biblioteca-ils.tec.mx/10.3390/sym14061237