Coahuila
# Preparación Base de Datos (Coahuila)
library(readr)
library(dplyr)
##
## 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
# 1. Lectura de datos
Base = read.csv("conjunto_de_datos_tper_vic1_envipe2025.csv", encoding="UTF-8")
# 2. Filtrar Coahuila y seleccionar variables:
Base_Coahuila <- Base %>%
filter(CVE_ENT == 5) %>%
select(
CASA = AP4_4_01,
TRABAJO = AP4_4_02,
CALLE = AP4_4_03,
ESCUELA = AP4_4_04,
MERCADO = AP4_4_05,
CENTRO_COMERCIAL = AP4_4_06,
BANCO = AP4_4_07,
CAJERO = AP4_4_08,
TRANSPORTE_PUBLICO = AP4_4_09,
AUTOMOVIL = AP4_4_10,
CARRETERA = AP4_4_11,
CENTRO_RECREATIVO = AP4_4_12
)
# 3. Verificar datos faltantes
summary(Base_Coahuila) #Si alguna variable tiene datos faltantes se marcarĆ”n en el resumen estadĆstico despuĆ©s del mĆ”ximo.
## CASA TRABAJO CALLE ESCUELA
## Min. :1.000 Min. :1.000 Min. :1.000 Min. :1.000
## 1st Qu.:1.000 1st Qu.:1.000 1st Qu.:1.000 1st Qu.:3.000
## Median :1.000 Median :1.000 Median :1.000 Median :3.000
## Mean :1.131 Mean :1.748 Mean :1.451 Mean :2.921
## 3rd Qu.:1.000 3rd Qu.:3.000 3rd Qu.:2.000 3rd Qu.:3.000
## Max. :9.000 Max. :9.000 Max. :9.000 Max. :9.000
## MERCADO CENTRO_COMERCIAL BANCO CAJERO
## Min. :1.000 Min. :1.000 Min. :1.000 Min. :1.000
## 1st Qu.:1.000 1st Qu.:1.000 1st Qu.:1.000 1st Qu.:1.000
## Median :1.000 Median :1.000 Median :1.000 Median :2.000
## Mean :1.455 Mean :1.278 Mean :1.553 Mean :1.689
## 3rd Qu.:2.000 3rd Qu.:1.000 3rd Qu.:2.000 3rd Qu.:2.000
## Max. :9.000 Max. :9.000 Max. :9.000 Max. :9.000
## TRANSPORTE_PUBLICO AUTOMOVIL CARRETERA CENTRO_RECREATIVO
## Min. :1.000 Min. :1.000 Min. :1.00 Min. :1.000
## 1st Qu.:1.000 1st Qu.:1.000 1st Qu.:1.00 1st Qu.:1.000
## Median :2.000 Median :1.000 Median :1.00 Median :1.000
## Mean :2.089 Mean :1.264 Mean :1.56 Mean :1.474
## 3rd Qu.:3.000 3rd Qu.:1.000 3rd Qu.:2.00 3rd Qu.:2.000
## Max. :9.000 Max. :9.000 Max. :9.00 Max. :9.000
# 4. Ver estructura de la base
cat("\nEstructura Base de Datos Coahuila:\n")
##
## Estructura Base de Datos Coahuila:
glimpse(Base_Coahuila)
## Rows: 2,670
## Columns: 12
## $ CASA <int> 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ā¦
## $ TRABAJO <int> 1, 1, 3, 1, 1, 1, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, ā¦
## $ CALLE <int> 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 2, 1, 1, ā¦
## $ ESCUELA <int> 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 3, 1, 3, 2, 3, ā¦
## $ MERCADO <int> 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 2, 1, 1, ā¦
## $ CENTRO_COMERCIAL <int> 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 2, 1, 1, ā¦
## $ BANCO <int> 1, 1, 1, 1, 1, 1, 2, 3, 1, 1, 1, 1, 1, 1, 1, 2, 1, ā¦
## $ CAJERO <int> 1, 1, 1, 1, 1, 1, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, ā¦
## $ TRANSPORTE_PUBLICO <int> 1, 1, 3, 3, 1, 1, 3, 3, 1, 1, 3, 1, 3, 3, 2, 1, 1, ā¦
## $ AUTOMOVIL <int> 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, ā¦
## $ CARRETERA <int> 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, ā¦
## $ CENTRO_RECREATIVO <int> 1, 1, 1, 1, 1, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 1, ā¦
# ĆNDICE DE PERCEPCIĆN DE SEGURIDAD - COAHUILA
# 5. Obtener el Ćndice de seguridad con base en la pregunta 4.4 sobre la percepción de seguridad en cuanto a delincuencia (una nueva columna de la proporción de 1=seguros de la pregunta APA4.4)
Base_Coahuila$Suma_Seguros <-
as.numeric(Base_Coahuila$CASA == 1) +
as.numeric(Base_Coahuila$TRABAJO == 1) +
as.numeric(Base_Coahuila$CALLE == 1) +
as.numeric(Base_Coahuila$ESCUELA == 1) +
as.numeric(Base_Coahuila$MERCADO == 1) +
as.numeric(Base_Coahuila$CENTRO_COMERCIAL == 1) +
as.numeric(Base_Coahuila$BANCO == 1) +
as.numeric(Base_Coahuila$CAJERO == 1) +
as.numeric(Base_Coahuila$TRANSPORTE_PUBLICO == 1) +
as.numeric(Base_Coahuila$AUTOMOVIL == 1) +
as.numeric(Base_Coahuila$CARRETERA == 1) +
as.numeric(Base_Coahuila$CENTRO_RECREATIVO == 1)
# Proporción de lugares seguros
Base_Coahuila$Indice_Seguridad <- Base_Coahuila$Suma_Seguros / 12
# Observar que se añadió la nueva variable (Indice_Seguridad)
names(Base_Coahuila)
## [1] "CASA" "TRABAJO" "CALLE"
## [4] "ESCUELA" "MERCADO" "CENTRO_COMERCIAL"
## [7] "BANCO" "CAJERO" "TRANSPORTE_PUBLICO"
## [10] "AUTOMOVIL" "CARRETERA" "CENTRO_RECREATIVO"
## [13] "Suma_Seguros" "Indice_Seguridad"
# Verificar el nuevo Ćndice
cat("RESUMEN DEL ĆNDICE DE SEGURIDAD (0 = Inseguro, 1 = Seguro):\n")
## RESUMEN DEL ĆNDICE DE SEGURIDAD (0 = Inseguro, 1 = Seguro):
summary(Base_Coahuila$Indice_Seguridad)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.0000 0.3333 0.5833 0.5618 0.7500 1.0000
# PRUEBA DE INDEPENDENCIA CHI-CUADRADA
# "En Coahuila, ĀæPodrĆamos inferir que hay dependencia entre la percepción de seguridad en tĆ©rminos de delincuencia y el tipo de lugar?
# Hipótesis:
# Ho: La percepción de seguridad es INDEPENDIENTE del tipo de lugar (No hay relación entre el lugar y qué tan seguro/inseguro se percibe)
# Ha: La percepción de seguridad DEPENDE del tipo de lugar (Existe relación entre el lugar y qué tan seguro/inseguro se percibe)
library(tidyr)
# 1. Crear base para anƔlisis
data_lugares <- Base_Coahuila %>%
select(CASA, TRABAJO, CALLE, ESCUELA, MERCADO, CENTRO_COMERCIAL,
BANCO, CAJERO, TRANSPORTE_PUBLICO, AUTOMOVIL, CARRETERA, CENTRO_RECREATIVO) %>%
pivot_longer(everything(), names_to = "LUGAR", values_to = "PERCEPCION") %>%
filter(PERCEPCION %in% c(1, 2)) # Solo Seguro (1) e Inseguro (2)
# 2. Tabla de contingencia
tabla <- table(data_lugares$LUGAR, data_lugares$PERCEPCION)
colnames(tabla) <- c("Seguro", "Inseguro")
cat("TABLA DE CONTINGENCIA - LUGAR vs PERCEPCIĆN:\n")
## TABLA DE CONTINGENCIA - LUGAR vs PERCEPCIĆN:
print(tabla)
##
## Seguro Inseguro
## AUTOMOVIL 2059 528
## BANCO 1518 839
## CAJERO 1176 1161
## CALLE 1523 1103
## CARRETERA 1336 1185
## CASA 2327 342
## CENTRO_COMERCIAL 2032 539
## CENTRO_RECREATIVO 1737 643
## ESCUELA 113 26
## MERCADO 1701 748
## TRABAJO 1578 200
## TRANSPORTE_PUBLICO 900 638
# Porcentajes por fila para mejor interpretación
cat("\nPORCENTAJES POR LUGAR (% Seguro vs % Inseguro):\n")
##
## PORCENTAJES POR LUGAR (% Seguro vs % Inseguro):
porcentajes <- prop.table(tabla, margin = 1) * 100
print(round(porcentajes, 1))
##
## Seguro Inseguro
## AUTOMOVIL 79.6 20.4
## BANCO 64.4 35.6
## CAJERO 50.3 49.7
## CALLE 58.0 42.0
## CARRETERA 53.0 47.0
## CASA 87.2 12.8
## CENTRO_COMERCIAL 79.0 21.0
## CENTRO_RECREATIVO 73.0 27.0
## ESCUELA 81.3 18.7
## MERCADO 69.5 30.5
## TRABAJO 88.8 11.2
## TRANSPORTE_PUBLICO 58.5 41.5
# 3. Prueba Chi-cuadrado de independencia
cat("\nPRUEBA CHI-CUADRADO DE INDEPENDENCIA:\n")
##
## PRUEBA CHI-CUADRADO DE INDEPENDENCIA:
chi_test <- chisq.test(tabla)
print(chi_test)
##
## Pearson's Chi-squared test
##
## data: tabla
## X-squared = 1966.5, df = 11, p-value < 2.2e-16
library(knitr)
library(kableExtra)
##
## Attaching package: 'kableExtra'
## The following object is masked from 'package:dplyr':
##
## group_rows
library(dplyr)
# 4. Verificación de Supuesto: las frecuencias de esperadas son mayores que 5
# Pasar tablas a data.frames (observados y esperados)
obs_mat <- as.data.frame.matrix(tabla)
exp_mat <- as.data.frame.matrix(chi_test$expected)
# Construir tabla resumen: 1 fila por LUGAR
tabla_resumen <- data.frame(
Lugar = rownames(obs_mat),
Frec_Esp_Seguro = round(exp_mat[, "Seguro"], 1),
Frec_Esp_Inseguro = round(exp_mat[, "Inseguro"], 1)
)
# Ordenar por lugar
tabla_resumen <- tabla_resumen %>% arrange(Lugar)
# Tabla
kable(tabla_resumen,
caption = "Frecuencias Esperadas en Coahuila",
format = "html",
col.names = c("Lugar",
"Frecuencia Esperada (Seguro)",
"Frecuencia Esperada (Inseguro)")
) %>%
kable_styling(
bootstrap_options = c("striped", "hover", "condensed", "responsive"),
full_width = FALSE,
position = "center"
) %>%
row_spec(0, bold = TRUE, color = "white", background = "#003f5c") %>% # encabezado bonito
column_spec(1, width = "3cm") %>%
column_spec(2, width = "4cm") %>%
column_spec(3, width = "5cm")
Frecuencias Esperadas en Coahuila
|
Lugar
|
Frecuencia Esperada (Seguro)
|
Frecuencia Esperada (Inseguro)
|
|
AUTOMOVIL
|
1794.3
|
792.7
|
|
BANCO
|
1634.8
|
722.2
|
|
CAJERO
|
1620.9
|
716.1
|
|
CALLE
|
1821.4
|
804.6
|
|
CARRETERA
|
1748.5
|
772.5
|
|
CASA
|
1851.2
|
817.8
|
|
CENTRO_COMERCIAL
|
1783.2
|
787.8
|
|
CENTRO_RECREATIVO
|
1650.7
|
729.3
|
|
ESCUELA
|
96.4
|
42.6
|
|
MERCADO
|
1698.6
|
750.4
|
|
TRABAJO
|
1233.2
|
544.8
|
|
TRANSPORTE_PUBLICO
|
1066.7
|
471.3
|
# 4. Interpretación
cat("\nINTERPRETACIĆN:\n")
##
## INTERPRETACIĆN:
cat("Como el valor de p (< 2.2e-16) es menor a alfa = 0.05 se tiene evidencia para rechazar Ho. Entonces lo mÔs probable es que la percepción de seguridad en términos de delincuencia DEPENDE del tipo de lugar (las variables no son independientes)")
## Como el valor de p (< 2.2e-16) es menor a alfa = 0.05 se tiene evidencia para rechazar Ho. Entonces lo mÔs probable es que la percepción de seguridad en términos de delincuencia DEPENDE del tipo de lugar (las variables no son independientes)
# 5. GrƔfica de barras apiladas
# Preparar datos para la grƔfica
datos_grafico <- as.data.frame(porcentajes)
colnames(datos_grafico) <- c("Lugar", "Percepcion", "Porcentaje")
datos_grafico$Percepcion <- factor(datos_grafico$Percepcion,
levels = c("Seguro", "Inseguro"))
library(ggplot2)
ggplot(datos_grafico, aes(x = Lugar, y = Porcentaje, fill = Percepcion)) +
geom_bar(stat = "identity", position = "stack") +
scale_fill_manual(values = c("Seguro" = "lightgreen", "Inseguro" = "lightcoral")) +
labs(title = "Percepción de Seguridad por Tipo de Lugar en Coahuila",
x = "Tipo de Lugar",
y = "Porcentaje (%)",
fill = "Percepción") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, hjust = 1),
plot.title = element_text(hjust = 0.5, face = "bold")) +
geom_text(aes(label = paste0(round(Porcentaje, 1), "%")),
position = position_stack(vjust = 0.5), size = 3)

Sinaloa
# Preparación Base de Datos (Sinaloa)
library(readr)
library(dplyr)
# 1. Lectura de datos
Base = read.csv("conjunto_de_datos_tper_vic1_envipe2025.csv", encoding="UTF-8")
# 2. Filtrar Sinaloa y seleccionar variables
Base_Sinaloa <- Base %>%
filter(CVE_ENT == 25) %>%
select(
CASA = AP4_4_01,
TRABAJO = AP4_4_02,
CALLE = AP4_4_03,
ESCUELA = AP4_4_04,
MERCADO = AP4_4_05,
CENTRO_COMERCIAL = AP4_4_06,
BANCO = AP4_4_07,
CAJERO = AP4_4_08,
TRANSPORTE_PUBLICO = AP4_4_09,
AUTOMOVIL = AP4_4_10,
CARRETERA = AP4_4_11,
CENTRO_RECREATIVO = AP4_4_12
)
# 3. Verificar datos faltantes
summary(Base_Sinaloa) #Si alguna variable tiene datos faltantes se marcarĆ”n en el resumen estadĆstico despuĆ©s del mĆ”ximo.
## CASA TRABAJO CALLE ESCUELA
## Min. :1.000 Min. :1.000 Min. :1.000 Min. :1.000
## 1st Qu.:1.000 1st Qu.:1.000 1st Qu.:1.000 1st Qu.:3.000
## Median :1.000 Median :2.000 Median :2.000 Median :3.000
## Mean :1.135 Mean :1.874 Mean :1.613 Mean :2.873
## 3rd Qu.:1.000 3rd Qu.:3.000 3rd Qu.:2.000 3rd Qu.:3.000
## Max. :9.000 Max. :9.000 Max. :9.000 Max. :9.000
## MERCADO CENTRO_COMERCIAL BANCO CAJERO
## Min. :1.000 Min. :1.000 Min. :1.000 Min. :1.000
## 1st Qu.:1.000 1st Qu.:1.000 1st Qu.:1.000 1st Qu.:1.000
## Median :2.000 Median :1.000 Median :2.000 Median :2.000
## Mean :1.638 Mean :1.555 Mean :1.779 Mean :1.842
## 3rd Qu.:2.000 3rd Qu.:2.000 3rd Qu.:2.000 3rd Qu.:2.000
## Max. :3.000 Max. :9.000 Max. :3.000 Max. :3.000
## TRANSPORTE_PUBLICO AUTOMOVIL CARRETERA CENTRO_RECREATIVO
## Min. :1.000 Min. :1.000 Min. :1.000 Min. :1.000
## 1st Qu.:1.000 1st Qu.:1.000 1st Qu.:1.000 1st Qu.:1.000
## Median :2.000 Median :1.000 Median :2.000 Median :2.000
## Mean :1.927 Mean :1.503 Mean :1.694 Mean :1.885
## 3rd Qu.:3.000 3rd Qu.:2.000 3rd Qu.:2.000 3rd Qu.:2.000
## Max. :9.000 Max. :9.000 Max. :9.000 Max. :9.000
# 4. Ver estructura de la base
cat("\nEstructura Base de Datos Sinaloa:\n")
##
## Estructura Base de Datos Sinaloa:
glimpse(Base_Sinaloa)
## Rows: 3,527
## Columns: 12
## $ CASA <int> 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ā¦
## $ TRABAJO <int> 1, 3, 1, 1, 1, 1, 2, 3, 1, 1, 1, 2, 1, 1, 1, 1, 1, ā¦
## $ CALLE <int> 1, 2, 1, 2, 1, 2, 1, 1, 2, 1, 1, 2, 1, 2, 1, 1, 1, ā¦
## $ ESCUELA <int> 3, 2, 3, 3, 3, 3, 3, 3, 1, 3, 3, 3, 3, 3, 3, 3, 1, ā¦
## $ MERCADO <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ā¦
## $ CENTRO_COMERCIAL <int> 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ā¦
## $ BANCO <int> 1, 2, 1, 3, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, ā¦
## $ CAJERO <int> 2, 2, 1, 3, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, ā¦
## $ TRANSPORTE_PUBLICO <int> 3, 2, 3, 2, 1, 3, 3, 1, 1, 1, 3, 3, 3, 1, 2, 1, 1, ā¦
## $ AUTOMOVIL <int> 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 2, 1, 1, ā¦
## $ CARRETERA <int> 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 2, 1, 1, 2, 1, 1, ā¦
## $ CENTRO_RECREATIVO <int> 1, 1, 1, 3, 3, 1, 1, 1, 1, 3, 3, 1, 1, 1, 1, 1, 1, ā¦
# ĆNDICE DE PERCEPCIĆN DE SEGURIDAD - SINALOA
# 5. Obtener el Ćndice de seguridad con base en la pregunta 4.4 sobre la percepción de seguridad en cuanto a delincuencia (una nueva columna de la proporción de 1=seguros de la pregunta APA4.4)
Base_Sinaloa$Suma_Seguros2 <-
as.numeric(Base_Sinaloa$CASA == 1) +
as.numeric(Base_Sinaloa$TRABAJO == 1) +
as.numeric(Base_Sinaloa$CALLE == 1) +
as.numeric(Base_Sinaloa$ESCUELA == 1) +
as.numeric(Base_Sinaloa$MERCADO == 1) +
as.numeric(Base_Sinaloa$CENTRO_COMERCIAL == 1) +
as.numeric(Base_Sinaloa$BANCO == 1) +
as.numeric(Base_Sinaloa$CAJERO == 1) +
as.numeric(Base_Sinaloa$TRANSPORTE_PUBLICO == 1) +
as.numeric(Base_Sinaloa$AUTOMOVIL == 1) +
as.numeric(Base_Sinaloa$CARRETERA == 1) +
as.numeric(Base_Sinaloa$CENTRO_RECREATIVO == 1)
# Proporción de lugares seguros
Base_Sinaloa$Indice_Seguridad2 <- Base_Sinaloa$Suma_Seguros2 / 12
# Observar que se añadió la nueva variable (Indice_Seguridad)
names(Base_Sinaloa)
## [1] "CASA" "TRABAJO" "CALLE"
## [4] "ESCUELA" "MERCADO" "CENTRO_COMERCIAL"
## [7] "BANCO" "CAJERO" "TRANSPORTE_PUBLICO"
## [10] "AUTOMOVIL" "CARRETERA" "CENTRO_RECREATIVO"
## [13] "Suma_Seguros2" "Indice_Seguridad2"
# Verificar el nuevo Ćndice
cat("RESUMEN DEL ĆNDICE DE SEGURIDAD (0 = Inseguro, 1 = Seguro):\n")
## RESUMEN DEL ĆNDICE DE SEGURIDAD (0 = Inseguro, 1 = Seguro):
summary(Base_Sinaloa$Indice_Seguridad2)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.0000 0.1667 0.4167 0.4192 0.6667 1.0000
# PRUEBA DE INDEPENDENCIA CHI-CUADRADA
# "En Sinaloa, ĀæPodrĆamos inferir que hay dependencia entre la percepción de seguridad en tĆ©rminos de delincuencia y el tipo de lugar?
# Hipótesis:
# Ho: La percepción de seguridad es INDEPENDIENTE del tipo de lugar (No hay relación entre el lugar y qué tan seguro/inseguro se percibe)
# Ha: La percepción de seguridad DEPENDE del tipo de lugar (Existe relación entre el lugar y qué tan seguro/inseguro se percibe)
library(tidyr)
# 1. Crear base para anƔlisis
data_lugares <- Base_Sinaloa %>%
select(CASA, TRABAJO, CALLE, ESCUELA, MERCADO, CENTRO_COMERCIAL,
BANCO, CAJERO, TRANSPORTE_PUBLICO, AUTOMOVIL, CARRETERA, CENTRO_RECREATIVO) %>%
pivot_longer(everything(), names_to = "LUGAR", values_to = "PERCEPCION") %>%
filter(PERCEPCION %in% c(1, 2)) # Solo Seguro (1) e Inseguro (2)
# 2. Tabla de contingencia
tabla <- table(data_lugares$LUGAR, data_lugares$PERCEPCION)
colnames(tabla) <- c("Seguro", "Inseguro")
cat("TABLA DE CONTINGENCIA - LUGAR vs PERCEPCIĆN:\n")
## TABLA DE CONTINGENCIA - LUGAR vs PERCEPCIĆN:
print(tabla)
##
## Seguro Inseguro
## AUTOMOVIL 1868 1551
## BANCO 1214 1880
## CAJERO 995 2094
## CALLE 1443 2017
## CARRETERA 1235 2144
## CASA 3058 468
## CENTRO_COMERCIAL 1829 1457
## CENTRO_RECREATIVO 1384 1484
## ESCUELA 181 128
## MERCADO 1659 1487
## TRABAJO 1699 611
## TRANSPORTE_PUBLICO 1179 1432
# Porcentajes por fila para mejor interpretación
cat("\nPORCENTAJES POR LUGAR (% Seguro vs % Inseguro):\n")
##
## PORCENTAJES POR LUGAR (% Seguro vs % Inseguro):
porcentajes <- prop.table(tabla, margin = 1) * 100
print(round(porcentajes, 1))
##
## Seguro Inseguro
## AUTOMOVIL 54.6 45.4
## BANCO 39.2 60.8
## CAJERO 32.2 67.8
## CALLE 41.7 58.3
## CARRETERA 36.5 63.5
## CASA 86.7 13.3
## CENTRO_COMERCIAL 55.7 44.3
## CENTRO_RECREATIVO 48.3 51.7
## ESCUELA 58.6 41.4
## MERCADO 52.7 47.3
## TRABAJO 73.5 26.5
## TRANSPORTE_PUBLICO 45.2 54.8
# 3. Prueba Chi-cuadrado de independencia
cat("\nPRUEBA CHI-CUADRADO DE INDEPENDENCIA:\n")
##
## PRUEBA CHI-CUADRADO DE INDEPENDENCIA:
chi_test <- chisq.test(tabla)
print(chi_test)
##
## Pearson's Chi-squared test
##
## data: tabla
## X-squared = 3381.4, df = 11, p-value < 2.2e-16
library(knitr)
library(kableExtra)
library(dplyr)
# 4. Verificación de Supuesto: las frecuencias de esperadas son mayores que 5
# Pasar tablas a data.frames (observados y esperados)
obs_mat <- as.data.frame.matrix(tabla)
exp_mat <- as.data.frame.matrix(chi_test$expected)
# Construir tabla resumen: 1 fila por LUGAR
tabla_resumen <- data.frame(
Lugar = rownames(obs_mat),
Frec_Esp_Seguro = round(exp_mat[, "Seguro"], 1),
Frec_Esp_Inseguro = round(exp_mat[, "Inseguro"], 1)
)
# Ordenar por lugar
tabla_resumen <- tabla_resumen %>% arrange(Lugar)
# Tabla
kable(tabla_resumen,
caption = "Frecuencias Esperadas en Sinaloa",
format = "html",
col.names = c("Lugar",
"Frecuencia Esperada (Seguro)",
"Frecuencia Esperada (Inseguro)")
) %>%
kable_styling(
bootstrap_options = c("striped", "hover", "condensed", "responsive"),
full_width = FALSE,
position = "center"
) %>%
row_spec(0, bold = TRUE, color = "white", background = "#003f5c") %>% # encabezado bonito
column_spec(1, width = "3cm") %>%
column_spec(2, width = "4cm") %>%
column_spec(3, width = "5cm")
Frecuencias Esperadas en Sinaloa
|
Lugar
|
Frecuencia Esperada (Seguro)
|
Frecuencia Esperada (Inseguro)
|
|
AUTOMOVIL
|
1758.6
|
1660.4
|
|
BANCO
|
1591.4
|
1502.6
|
|
CAJERO
|
1588.9
|
1500.1
|
|
CALLE
|
1779.7
|
1680.3
|
|
CARRETERA
|
1738.0
|
1641.0
|
|
CASA
|
1813.6
|
1712.4
|
|
CENTRO_COMERCIAL
|
1690.2
|
1595.8
|
|
CENTRO_RECREATIVO
|
1475.2
|
1392.8
|
|
ESCUELA
|
158.9
|
150.1
|
|
MERCADO
|
1618.2
|
1527.8
|
|
TRABAJO
|
1188.2
|
1121.8
|
|
TRANSPORTE_PUBLICO
|
1343.0
|
1268.0
|
# 4. Interpretación
cat("\nINTERPRETACIĆN:\n")
##
## INTERPRETACIĆN:
cat("Como el valor de p (< 2.2e-16) es menor a alfa = 0.05 se tiene evidencia para rechazar Ho. Entonces lo mÔs probable es que la percepción de seguridad en términos de delincuencia DEPENDE del tipo de lugar (las variables no son independientes)")
## Como el valor de p (< 2.2e-16) es menor a alfa = 0.05 se tiene evidencia para rechazar Ho. Entonces lo mÔs probable es que la percepción de seguridad en términos de delincuencia DEPENDE del tipo de lugar (las variables no son independientes)
# 5. GrƔfica de barras apiladas
# Preparar datos para la grƔfica
datos_grafico <- as.data.frame(porcentajes)
colnames(datos_grafico) <- c("Lugar", "Percepcion", "Porcentaje")
datos_grafico$Percepcion <- factor(datos_grafico$Percepcion,
levels = c("Seguro", "Inseguro"))
library(ggplot2)
ggplot(datos_grafico, aes(x = Lugar, y = Porcentaje, fill = Percepcion)) +
geom_bar(stat = "identity", position = "stack") +
scale_fill_manual(values = c("Seguro" = "lightgreen", "Inseguro" = "lightcoral")) +
labs(title = "Percepción de Seguridad por Tipo de Lugar en Sinaloa",
x = "Tipo de Lugar",
y = "Porcentaje (%)",
fill = "Percepción") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, hjust = 1),
plot.title = element_text(hjust = 0.5, face = "bold")) +
geom_text(aes(label = paste0(round(Porcentaje, 1), "%")),
position = position_stack(vjust = 0.5), size = 3)
