La base de datos USArrests contiene estadísticas en arrestos por cada 100,000 residentes por agresión, asesinato y violación en cada uno de los 50 estados de E.E.U.U. en 1973.
#install.packages("caret") # Algoritmos de aprendizaje automático
library(caret)
#install.packages("datasets") # Para usar la base de datos "USArrests"
library(datasets)
#install.packages("ggplot2") # Gráficas con mejor diseño
library(ggplot2)
#install.packages("lattice") # Crear gráficos
library(lattice)
#install.packages("DataExplorer") # Análisis Descriptivo
library(DataExplorer)
#install.packages("kernlab") # Modelos de SVM
library(kernlab)
#install.packages("dplyr") # Manipulación de datos
library(dplyr)
library(cluster)
library(factoextra)
library(data.table)
library(tidyverse)
#install.packages("tigris")
library(tigris)
library(randomForest)
library(sf)
library(shiny)
datos <- USArrests
datos_escalados <- scale(datos)
options(tigris_use_cache = TRUE)
us_map <- tigris::states(cb = TRUE)
## Retrieving data for the year 2021
## | | | 0% | |= | 1% | |= | 2% | |== | 2% | |== | 3% | |=== | 4% | |==== | 5% | |==== | 6% | |===== | 7% | |===== | 8% | |====== | 8% | |====== | 9% | |======= | 10% | |======== | 11% | |======== | 12% | |========= | 12% | |========= | 13% | |========== | 14% | |========== | 15% | |=========== | 15% | |=========== | 16% | |============ | 17% | |============ | 18% | |============= | 18% | |============= | 19% | |============== | 19% | |============== | 20% | |============== | 21% | |=============== | 21% | |=============== | 22% | |================ | 23% | |================ | 24% | |================= | 24% | |================== | 26% | |=================== | 27% | |==================== | 28% | |==================== | 29% | |===================== | 29% | |===================== | 30% | |===================== | 31% | |====================== | 31% | |====================== | 32% | |======================= | 33% | |======================== | 34% | |========================= | 35% | |========================= | 36% | |========================== | 37% | |========================== | 38% | |=========================== | 39% | |=============================== | 44% | |================================ | 45% | |================================ | 46% | |================================= | 47% | |================================= | 48% | |================================== | 48% | |=================================== | 50% | |==================================== | 51% | |======================================= | 56% | |======================================== | 57% | |========================================= | 58% | |========================================== | 59% | |============================================= | 64% | |================================================ | 68% | |================================================ | 69% | |================================================= | 70% | |================================================== | 71% | |=================================================== | 73% | |===================================================== | 76% | |====================================================== | 77% | |======================================================= | 78% | |======================================================== | 81% | |========================================================= | 82% | |========================================================== | 83% | |=========================================================== | 84% | |=========================================================== | 85% | |============================================================ | 86% | |============================================================= | 86% | |============================================================= | 87% | |============================================================= | 88% | |============================================================== | 88% | |=============================================================== | 90% | |================================================================ | 91% | |=================================================================== | 95% | |======================================================================| 100%
set.seed(123)
segmentos <- kmeans(datos_escalados, centers = 4, nstart = 25)
asignacion <- cbind(datos, cluster = segmentos$cluster)
asignacion$state <- tolower(rownames(asignacion))
us_map$NAME <- tolower(us_map$NAME)
asignacion$nivel_seguridad <- factor(case_when(
asignacion$cluster == 1 ~ "Bajo",
asignacion$cluster == 2 ~ "Medio",
asignacion$cluster == 3 ~ "Alto",
asignacion$cluster == 4 ~ "Muy Alto",
TRUE ~ "Desconocido"
))
modelo_rf <- randomForest(
nivel_seguridad ~ Murder + Assault + Rape + UrbanPop,
data = asignacion,
ntree = 100
)
ui <- fluidPage(
titlePanel("Predicción de Seguridad en EE.UU."),
sidebarLayout(
sidebarPanel(
h4("Ingrese sus datos para predicción"),
numericInput("murder", "Asesinatos por 100,000 hab.:", value = 10, min = 0),
numericInput("assault", "Agresiones por 100,000 hab.:", value = 200, min = 0),
numericInput("rape", "Violaciones por 100,000 hab.:", value = 20, min = 0),
numericInput("urbanpop", "Porcentaje de población urbana:", value = 50, min = 0, max = 100),
actionButton("predict", "Predecir Seguridad"),
hr(),
h4("Predicción del nivel de seguridad"),
verbatimTextOutput("prediction_output")
),
mainPanel(
tabsetPanel(
tabPanel("Mapa de Seguridad",
plotOutput("mapaPlot")
),
tabPanel("Estados Más y Menos Seguros",
tableOutput("top5_safe"),
tableOutput("top5_unsafe")
)
)
)
)
)
# Servidor (Server)
server <- function(input, output, session) {
# Predecir el nivel de seguridad basado en la entrada del usuario
observeEvent(input$predict, {
new_data <- data.frame(
Murder = input$murder,
Assault = input$assault,
Rape = input$rape,
UrbanPop = input$urbanpop
)
prediccion <- predict(modelo_rf, new_data)
output$prediction_output <- renderPrint({ paste("Nivel de Seguridad:", prediccion) })
})
# Graficar el mapa con los clusters de seguridad
output$mapaPlot <- renderPlot({
us_clustered <- left_join(us_map, asignacion, by = c("NAME" = "state"))
colores_seguridad <- c("Bajo" = "darkgreen",
"Medio" = "yellow",
"Alto" = "orange",
"Muy Alto" = "red")
ggplot(data = us_clustered) +
geom_sf(aes(fill = nivel_seguridad), color = "black", size = 0.3) +
scale_fill_manual(values = colores_seguridad, name = "Nivel de Seguridad") +
labs(title = "Mapa de Seguridad en EE.UU. (1973)",
subtitle = "Clasificación basada en tasas de criminalidad",
caption = "Fuente: USArrests") +
theme_minimal()
})
output$top5_safe <- renderTable({
asignacion %>%
arrange(Murder + Assault + Rape) %>%
head(5) %>%
select(state, Murder, Assault, Rape, nivel_seguridad)
}, caption = "🟢 Estados Más Seguros")
output$top5_unsafe <- renderTable({
asignacion %>%
arrange(desc(Murder + Assault + Rape)) %>%
head(5) %>%
select(state, Murder, Assault, Rape, nivel_seguridad)
}, caption = "🔴 Estados Más Inseguros")
}
shinyApp(ui = ui, server = server)