library(readr)
library(openxlsx)
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.1.2 ✔ purrr 1.0.1
## ✔ forcats 1.0.0 ✔ stringr 1.5.0
## ✔ ggplot2 3.4.2 ✔ tibble 3.2.1
## ✔ lubridate 1.9.2 ✔ tidyr 1.3.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(factoextra)
## Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa
library(cowplot)
##
## Attaching package: 'cowplot'
##
## The following object is masked from 'package:lubridate':
##
## stamp
library(ggpubr)
##
## Attaching package: 'ggpubr'
##
## The following object is masked from 'package:cowplot':
##
## get_legend
library(cluster)
library(purrr)
library(dplyr)
library(readxl)
#install.packages("rsconnect")
#file.choose()
#ev1 <- read_excel("/Users/danielnajera/Desktop/Evidencia1/atus_00.xlsx", col_names = TRUE)
ev1 <- read.xlsx("C:\\Users\\danbr\\OneDrive\\Desktop\\Mineria de Datos\\Evidencia 1\\atus_00.xlsx")
#view(ev1)
La siguiente base de datos nos muestra los delitos ocurridos, delitos sin carpeta de investigación y delitos en los cuáles no se especifica si se denunció o se abrió carpeta de investigación (cifras negras) por entidad federativa de México.
ev1 <- ev1 %>%
column_to_rownames(var = "Entidad_federativa")
#view(ev1)
evidencia1 = scale(ev1, center = TRUE, scale = TRUE)
#summary(evi1)
delitos = as.data.frame(evidencia1)
entidad=rownames(evidencia1)
#view(evidencia1)
total_within = function(n_clusters, data, iter.max=1000, nstart=50){
cluster_means = kmeans(data,centers = n_clusters,
iter.max = iter.max,
nstart = nstart)
return(cluster_means$tot.withinss)
}
total_withinss <- map_dbl(.x = 1:15,
.f = total_within,
data = delitos)
total_withinss
## [1] 93.0000000 42.6586334 20.5760164 12.6719182 8.9899054 6.2907432
## [7] 4.8270774 3.6765619 2.6516236 2.1371952 1.6949681 1.1243269
## [13] 0.9377229 0.7762072 0.6883012
data.frame(n_clusters = 1:15, suma_cuadrados_internos = total_withinss) %>%
ggplot(aes(x = n_clusters, y = suma_cuadrados_internos)) +
geom_line() +
geom_point() +
scale_x_continuous(breaks = 1:15) +
labs(title = "Suma total de cuadrados intra-cluster") +
theme_bw()
kmcluster = kmeans(delitos,centers=3,nstart = 50)
kmcluster
## K-means clustering with 3 clusters of sizes 24, 7, 1
##
## Cluster means:
## Delitos_ocurridos1 Delitos_sin_carpeta_de_investigación Cifra_negra2
## 1 -0.2760414 -0.2578792 0.4120830
## 2 0.2474897 0.1763185 -1.4884843
## 3 4.8925653 4.9548704 0.5293988
##
## Clustering vector:
## Aguascalientes Baja California
## 1 2
## Baja California Sur Campeche
## 1 1
## Coahuila de Zaragoza Colima
## 1 1
## Chiapas Chihuahua
## 1 1
## Ciudad de México Durango
## 3 1
## Guanajuato Guerrero
## 2 1
## Hidalgo Jalisco
## 1 2
## Estado de México Michoacán de Ocampo
## 2 1
## Morelos Nayarit
## 1 1
## Nuevo León Oaxaca
## 2 1
## Puebla Querétaro
## 1 1
## Quintana Roo San Luis Potosí
## 1 1
## Sinaloa Sonora
## 1 1
## Tabasco Tamaulipas
## 2 1
## Tlaxcala Veracruz de Ignacio de la Llave
## 1 2
## Yucatán Zacatecas
## 1 1
##
## Within cluster sum of squares by cluster:
## [1] 9.23665 11.33937 0.00000
## (between_SS / total_SS = 77.9 %)
##
## Available components:
##
## [1] "cluster" "centers" "totss" "withinss" "tot.withinss"
## [6] "betweenss" "size" "iter" "ifault"
delitos = delitos %>% mutate(cluster = kmcluster$cluster)
(g1=ggplot(delitos, aes(x = Delitos_sin_carpeta_de_investigación, y = Delitos_ocurridos1)) +
geom_point(aes(color=as.factor(cluster)), size=10)+
geom_text(aes(label = cluster), size = 5) +
theme_bw() +
theme(legend.position = "none")+
labs(title = "Delitos ocurridos sin carpeta de investigación")
)
fviz_cluster(kmcluster, delitos)+
theme_minimal()
rownames(delitos)=entidad
fviz_cluster(kmcluster, delitos, show.clust.cent = T,
ellipse.type = "euclid", star.plot = T, repel = T) +
labs(title = "Resultados clustering K-means") +
theme_bw()
## Too few points to calculate an ellipse
En este caso eliminamos la “Ciudad de México”, ya que al tener una gran población también tenía una gran cantidad de delitos, por lo que no nos permitía analizar los demás.
evidencia1_2 <- ev1[-9, ]
#view(evidencia1_2)
delitos_2 = as.data.frame(evidencia1_2)
entidad_2 = rownames(evidencia1_2)
#view(evidencia1_2)
total_within_2 = function(n_clusters, data, iter.max=1000, nstart=50){
cluster_means_2 = kmeans(data,centers = n_clusters,
iter.max = iter.max,
nstart = nstart)
return(cluster_means_2$tot.withinss)
}
total_withinss_2 <- map_dbl(.x = 1:15,
.f = total_within_2,
data = delitos_2)
total_withinss_2
## [1] 132600126147 46294653754 18792579675 11144595912 5331747760
## [6] 2736574936 1969901867 1396691733 1202600476 1007590109
## [11] 667399134 521149445 494220960 396437796 561409542
data.frame(n_clusters = 1:15, suma_cuadrados_internos = total_withinss_2) %>%
ggplot(aes(x = n_clusters, y = suma_cuadrados_internos)) +
geom_line() +
geom_point() +
scale_x_continuous(breaks = 1:15) +
labs(title = "Suma total de cuadrados intra-cluster") +
theme_bw()
kmcluster_2 = kmeans(delitos_2,centers=4,nstart = 50)
kmcluster_2
## K-means clustering with 4 clusters of sizes 7, 17, 6, 1
##
## Cluster means:
## Delitos_ocurridos1 Delitos_sin_carpeta_de_investigación Cifra_negra2
## 1 79260.17 72401.67 91.14473
## 2 39372.31 36704.65 93.14687
## 3 129511.85 115126.06 88.81502
## 4 246216.69 219113.10 88.99198
##
## Clustering vector:
## Aguascalientes Baja California
## 2 1
## Baja California Sur Campeche
## 2 2
## Coahuila de Zaragoza Colima
## 2 2
## Chiapas Chihuahua
## 2 2
## Durango Guanajuato
## 1 3
## Guerrero Hidalgo
## 2 2
## Jalisco Estado de México
## 3 4
## Michoacán de Ocampo Morelos
## 1 2
## Nayarit Nuevo León
## 2 1
## Oaxaca Puebla
## 3 3
## Querétaro Quintana Roo
## 3 2
## San Luis Potosí Sinaloa
## 1 1
## Sonora Tabasco
## 1 2
## Tamaulipas Tlaxcala
## 2 2
## Veracruz de Ignacio de la Llave Yucatán
## 3 2
## Zacatecas
## 2
##
## Within cluster sum of squares by cluster:
## [1] 920768100 3740269950 6483557862 0
## (between_SS / total_SS = 91.6 %)
##
## Available components:
##
## [1] "cluster" "centers" "totss" "withinss" "tot.withinss"
## [6] "betweenss" "size" "iter" "ifault"
delitos_2 = delitos_2 %>% mutate(cluster = kmcluster_2$cluster)
(g1=ggplot(delitos_2, aes(x = Delitos_sin_carpeta_de_investigación, y = Delitos_ocurridos1)) +
geom_point(aes(color=as.factor(cluster)), size=10)+
geom_text(aes(label = cluster), size = 5) +
theme_bw() +
theme(legend.position = "none")+
labs(title = "Delitos ocurridos sin carpeta de investigación sin CDMX")
)
rownames(delitos_2)=entidad_2
fviz_cluster(kmcluster_2, delitos_2, show.clust.cent = T,
ellipse.type = "euclid", star.plot = T, repel = T) +
labs(title = "Resultados clustering K-means") +
theme_bw()
## Too few points to calculate an ellipse
En este caso eliminamos el “Estado de México”, ya que debido a su gran población tiene una gran cantidad de delitos, por lo que nos dificulta la vista de las demás entidades, de esta forma podemos hacer un análisis más detallado de esas entidades.
evidencia1_3 <- evidencia1_2[-14, ]
view(evidencia1_3)
delitos_3 = as.data.frame(evidencia1_3)
entidad_3 = rownames(evidencia1_3)
#view(evidencia1_3)
total_within_3 = function(n_clusters, data, iter.max=1000, nstart=50){
cluster_means_3 = kmeans(data,centers = n_clusters,
iter.max = iter.max,
nstart = nstart)
return(cluster_means_3$tot.withinss)
}
total_withinss_3 <- map_dbl(.x = 1:15,
.f = total_within_2,
data = delitos_2)
total_withinss_3
## [1] 132600126164 46294653760 18792579686 10340627324 5331747764
## [6] 2736574940 1969901870 1396691733 1170135253 1012022263
## [11] 814109238 647319492 582907066 411167702 253282782
data.frame(n_clusters = 1:15, suma_cuadrados_internos = total_withinss_3) %>%
ggplot(aes(x = n_clusters, y = suma_cuadrados_internos)) +
geom_line() +
geom_point() +
scale_x_continuous(breaks = 1:15) +
labs(title = "Suma total de cuadrados intra-cluster") +
theme_bw()
kmcluster_3 = kmeans(delitos_3,centers=3,nstart = 50)
kmcluster_3
## K-means clustering with 3 clusters of sizes 17, 10, 3
##
## Cluster means:
## Delitos_ocurridos1 Delitos_sin_carpeta_de_investigación Cifra_negra2
## 1 39372.31 36704.65 93.14687
## 2 88621.57 79807.93 90.27120
## 3 148558.87 133162.90 89.39707
##
## Clustering vector:
## Aguascalientes Baja California
## 1 2
## Baja California Sur Campeche
## 1 1
## Coahuila de Zaragoza Colima
## 1 1
## Chiapas Chihuahua
## 1 1
## Durango Guanajuato
## 2 3
## Guerrero Hidalgo
## 1 1
## Jalisco Michoacán de Ocampo
## 2 2
## Morelos Nayarit
## 1 1
## Nuevo León Oaxaca
## 2 2
## Puebla Querétaro
## 3 2
## Quintana Roo San Luis Potosí
## 1 2
## Sinaloa Sonora
## 2 2
## Tabasco Tamaulipas
## 1 1
## Tlaxcala Veracruz de Ignacio de la Llave
## 1 3
## Yucatán Zacatecas
## 1 1
##
## Within cluster sum of squares by cluster:
## [1] 3740269950 4428639091 2171718275
## (between_SS / total_SS = 86.6 %)
##
## Available components:
##
## [1] "cluster" "centers" "totss" "withinss" "tot.withinss"
## [6] "betweenss" "size" "iter" "ifault"
delitos_3 = delitos_3 %>% mutate(cluster = kmcluster_3$cluster)
g1 <- ggplot(delitos_3, aes(x = Delitos_sin_carpeta_de_investigación, y = Delitos_ocurridos1)) +
geom_point(aes(color = as.factor(cluster)), size = 3) +
geom_text(aes(label = cluster), size = 3, vjust = -0.5) +
theme_minimal() +
labs(title = "Delitos ocurridos sin carpeta de investigación sin CDMX y EdoMx")
g1
rownames(delitos_3)=entidad_3
fviz_cluster(kmcluster_3, delitos_3, show.clust.cent = T,
ellipse.type = "euclid", star.plot = T, repel = T) +
labs(title = "Resultados clustering K-means") +
theme_bw()
## Too few points to calculate an ellipse
fviz_cluster(kmcluster_3, delitos_3)+
theme_minimal()
Al final pudimos ver qué entidades son las más seguras y al mismo tiempo cuáles las más inseguras, por otro lado, cuáles son las que tienen más delitos sin carpeta de investigación, lo cual puede hablar mal de la entidad, ya que lo que la gente busca es que haya con justicia.