# ============================================================
# POSTER INDIVIDUAL - Paula Garza Paniagua A00843704
# Edad y percepción de seguridad en Nuevo León - ENVIPE 2025
# ============================================================

library(knitr)

# --- CARGA DE DATOS ---
load("C:/Users/garza/Downloads/BD_ENVIPE_2025.RData")

vars_seguridad <- sprintf("AP4_4_%02d", 1:12)

# --- FILTRAR NUEVO LEÓN Y LIMPIAR ---
base_nl <- TPer_Vic1[, c("EDAD", "CVE_ENT", vars_seguridad)]
base_nl <- subset(base_nl, CVE_ENT == 19)
base_nl <- na.omit(base_nl)
base_nl <- subset(base_nl, EDAD >= 18 & EDAD <= 97)

# Convertir a numérico
base_nl$EDAD <- as.numeric(base_nl$EDAD)

# --- ÍNDICE DE PERCEPCIÓN DE SEGURIDAD ---
base_nl$indice_seguridad <- rowSums(base_nl[, vars_seguridad] == 1) / 12

cat("n =", nrow(base_nl), "\n")
## n = 2677
# --- ANÁLISIS DESCRIPTIVO ---
desc <- data.frame(
  Variable = c("Edad", "Índice de seguridad"),
  n        = c(nrow(base_nl), nrow(base_nl)),
  Media    = c(mean(base_nl$EDAD), mean(base_nl$indice_seguridad)),
  DE       = c(sd(base_nl$EDAD),   sd(base_nl$indice_seguridad)),
  Minimo   = c(min(base_nl$EDAD),  min(base_nl$indice_seguridad)),
  Maximo   = c(max(base_nl$EDAD),  max(base_nl$indice_seguridad))
)
knitr::kable(desc, digits = 4, 
             caption = "Descripción de variables - Nuevo León")
Descripción de variables - Nuevo León
Variable n Media DE Minimo Maximo
Edad 2677 44.4636 16.8910 18 95
Índice de seguridad 2677 0.4353 0.2491 0 1
# --- SCATTERPLOT ---
plot(
  base_nl$EDAD,
  base_nl$indice_seguridad,
  pch  = 16,
  col  = rgb(0.1, 0.35, 0.55, 0.2),
  xlab = "Edad",
  ylab = "Índice de percepción de seguridad",
  main = "Edad e índice de seguridad — Nuevo León"
)
abline(lm(indice_seguridad ~ EDAD, data = base_nl), col = "#c0392b", lwd = 2)

# --- CORRELACIONES ---
fmt_p <- function(p) ifelse(p < 0.001, "< 0.001", formatC(p, format = "f", digits = 4))

base_nl$EDAD <- as.numeric(base_nl$EDAD)
base_nl$indice_seguridad <- as.numeric(base_nl$indice_seguridad)

cor_p <- cor.test(base_nl$EDAD, base_nl$indice_seguridad, method = "pearson")
cor_s <- cor.test(base_nl$EDAD, base_nl$indice_seguridad, method = "spearman", exact = FALSE)

tabla_cor <- data.frame(
  Prueba      = c("Pearson", "Spearman"),
  Correlacion = c(as.numeric(cor_p$estimate), as.numeric(cor_s$estimate)),
  p_valor     = fmt_p(c(cor_p$p.value, cor_s$p.value))
)
knitr::kable(tabla_cor, digits = 4, 
             caption = "Pruebas de correlación — Nuevo León")
Pruebas de correlación — Nuevo León
Prueba Correlacion p_valor
Pearson -0.1771 < 0.001
Spearman -0.1701 < 0.001