# ============================================================
#   ANÁLISIS ESTADÍSTICO – DERECHOS HUMANOS
#   Dataset: Base_Derechos_humanos.xlsx
#   Incluye: Spearman, t-test, Chi-cuadrado, ANOVA, regresión
#   + Gráficos de caja, dispersión y barras
# ============================================================

library(readxl)
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.1     ✔ stringr   1.6.0
## ✔ ggplot2   4.0.0     ✔ tibble    3.3.0
## ✔ lubridate 1.9.4     ✔ tidyr     1.3.1
## ✔ purrr     1.2.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(ggplot2)

# ------------------------------------------------------------
# 1. CARGA DEL ARCHIVO
# ------------------------------------------------------------

datos <- read_excel("Base_Derechos_Humanos.xlsx")

# ------------------------------------------------------------
# 2. CODIFICACIÓN DE VARIABLES
# ------------------------------------------------------------
datos <- datos %>%
  mutate(
    sexo = factor(sexo),
    nivel_educativo = ordered(nivel_educativo,
                              levels = c("Secundaria", "Técnico", "Universitario", "Postgrado")),
    conocimiento_ddhh = ordered(conocimiento_ddhh,
                                levels = c("Bajo", "Medio", "Alto")),
    percepcion_respeto_ddhh = as.numeric(percepcion_respeto_ddhh),
    ha_denunciado_vulneracion = factor(ha_denunciado_vulneracion,
                                       levels = c("No", "Sí")),
    confianza_instituciones_ddhh = as.numeric(confianza_instituciones_ddhh),
    frecuencia_educacion_ddhh = factor(frecuencia_educacion_ddhh,
                                       levels = c("Nunca", "Baja", "Media", "Alta")),
    apoyo_organizaciones_ddhh = factor(apoyo_organizaciones_ddhh,
                                       levels = c("No", "Sí")),
    participacion_actividades_ddhh = factor(participacion_actividades_ddhh,
                                            levels = c("No", "Sí")),
    satisfaccion_garantias_ddhh = as.numeric(satisfaccion_garantias_ddhh)
  )


# ============================================================
#   SUB-PREGUNTA 1
#   ¿Conocimiento en DDHH se asocia con percepción de respeto?
# ============================================================

# --- Estadística (Spearman)
cor_cono_respeto <- cor.test(as.numeric(datos$conocimiento_ddhh),
                             datos$percepcion_respeto_ddhh,
                             method="spearman")
## Warning in cor.test.default(as.numeric(datos$conocimiento_ddhh),
## datos$percepcion_respeto_ddhh, : Cannot compute exact p-value with ties
cor_cono_respeto
## 
##  Spearman's rank correlation rho
## 
## data:  as.numeric(datos$conocimiento_ddhh) and datos$percepcion_respeto_ddhh
## S = 160649, p-value = 0.7221
## alternative hypothesis: true rho is not equal to 0
## sample estimates:
##        rho 
## 0.03601147
# --- Gráfico: Boxplot percepción según conocimiento
ggplot(datos, aes(x = conocimiento_ddhh, y = percepcion_respeto_ddhh, fill = conocimiento_ddhh)) +
  geom_boxplot() +
  labs(title="Percepción del Respeto según Conocimiento en DDHH",
       x="Conocimiento en DDHH",
       y="Percepción del respeto (1–10)") +
  theme_minimal()

# ============================================================
#   SUB-PREGUNTA 2
#   ¿Participar/apoyar organizaciones aumenta satisfacción?
# ============================================================

# --- t-test para participación
t_part <- t.test(satisfaccion_garantias_ddhh ~ participacion_actividades_ddhh,
                 data=datos)
t_part
## 
##  Welch Two Sample t-test
## 
## data:  satisfaccion_garantias_ddhh by participacion_actividades_ddhh
## t = -0.040882, df = 52.822, p-value = 0.9675
## alternative hypothesis: true difference in means between group No and group Sí is not equal to 0
## 95 percent confidence interval:
##  -1.361675  1.307280
## sample estimates:
## mean in group No mean in group Sí 
##         5.352113         5.379310
# --- t-test para apoyo
t_apoyo <- t.test(satisfaccion_garantias_ddhh ~ apoyo_organizaciones_ddhh,
                  data=datos)
t_apoyo
## 
##  Welch Two Sample t-test
## 
## data:  satisfaccion_garantias_ddhh by apoyo_organizaciones_ddhh
## t = 1.4036, df = 84.079, p-value = 0.1641
## alternative hypothesis: true difference in means between group No and group Sí is not equal to 0
## 95 percent confidence interval:
##  -0.3518641  2.0404098
## sample estimates:
## mean in group No mean in group Sí 
##         5.891892         5.047619
# --- Gráfico de caja: satisfacción según participación
ggplot(datos, aes(x = participacion_actividades_ddhh, 
                  y = satisfaccion_garantias_ddhh, 
                  fill = participacion_actividades_ddhh)) +
  geom_boxplot() +
  labs(title="Satisfacción según Participación en Actividades DDHH",
       x="Participó en actividades",
       y="Satisfacción con garantías") +
  theme_minimal()

# --- Gráfico de caja: satisfacción según apoyo
ggplot(datos, aes(x = apoyo_organizaciones_ddhh, 
                  y = satisfaccion_garantias_ddhh, 
                  fill = apoyo_organizaciones_ddhh)) +
  geom_boxplot() +
  labs(title="Satisfacción según Apoyo a Organizaciones DDHH",
       x="Apoya organizaciones",
       y="Satisfacción con garantías") +
  theme_minimal()

# ============================================================
#   SUB-PREGUNTA 3
#   ¿Confianza institucional se relaciona con percepción?
# ============================================================

cor_confianza <- cor.test(datos$confianza_instituciones_ddhh,
                          datos$percepcion_respeto_ddhh,
                          method="spearman")
## Warning in cor.test.default(datos$confianza_instituciones_ddhh,
## datos$percepcion_respeto_ddhh, : Cannot compute exact p-value with ties
cor_confianza
## 
##  Spearman's rank correlation rho
## 
## data:  datos$confianza_instituciones_ddhh and datos$percepcion_respeto_ddhh
## S = 167151, p-value = 0.9763
## alternative hypothesis: true rho is not equal to 0
## sample estimates:
##          rho 
## -0.003003377
# --- Gráfico de dispersión
ggplot(datos, aes(x=confianza_instituciones_ddhh,
                  y=percepcion_respeto_ddhh)) +
  geom_point(color="blue", alpha=0.6) +
  geom_smooth(method="lm", color="red") +
  labs(title="Relación entre Confianza Institucional y Percepción del Respeto",
       x="Confianza (1–10)",
       y="Percepción del respeto (1–10)") +
  theme_minimal()
## `geom_smooth()` using formula = 'y ~ x'

# ============================================================
#   SUB-PREGUNTA 4
#   ¿Educación en DDHH influye en haber denunciado?
# ============================================================

tabla_edu_den <- table(datos$frecuencia_educacion_ddhh, datos$ha_denunciado_vulneracion)
chisq.test(tabla_edu_den)
## Warning in chisq.test(tabla_edu_den): Chi-squared approximation may be
## incorrect
## 
##  Pearson's Chi-squared test
## 
## data:  tabla_edu_den
## X-squared = 8.7442, df = 3, p-value = 0.03289
# --- Gráfico de barras
ggplot(datos, aes(x=frecuencia_educacion_ddhh, fill=ha_denunciado_vulneracion)) +
  geom_bar(position="fill") +
  labs(title="Relación entre Educación en DDHH y Denuncias",
       x="Frecuencia de educación",
       y="Proporción") +
  theme_minimal()

# ============================================================
#   SUB-PREGUNTA 5
#   ¿Nivel educativo influye en el apoyo a causas DDHH?
# ============================================================

tabla_nivel_apoyo <- table(datos$nivel_educativo, datos$apoyo_organizaciones_ddhh)
chisq.test(tabla_nivel_apoyo)
## 
##  Pearson's Chi-squared test
## 
## data:  tabla_nivel_apoyo
## X-squared = 4.7764, df = 3, p-value = 0.1889
# --- Gráfico de barras
ggplot(datos, aes(x=nivel_educativo, fill=apoyo_organizaciones_ddhh)) +
  geom_bar(position="fill") +
  labs(title="Apoyo a Organizaciones según Nivel Educativo",
       x="Nivel educativo",
       y="Proporción") +
  theme_minimal()

# ============================================================
#   ANOVA
#   ¿La satisfacción cambia según educación en DDHH?
# ============================================================

anova_model <- aov(satisfaccion_garantias_ddhh ~ frecuencia_educacion_ddhh, data = datos)
summary(anova_model)
##                           Df Sum Sq Mean Sq F value Pr(>F)  
## frecuencia_educacion_ddhh  3   63.5  21.177   2.416 0.0712 .
## Residuals                 96  841.5   8.766                 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
TukeyHSD(anova_model)
##   Tukey multiple comparisons of means
##     95% family-wise confidence level
## 
## Fit: aov(formula = satisfaccion_garantias_ddhh ~ frecuencia_educacion_ddhh, data = datos)
## 
## $frecuencia_educacion_ddhh
##                   diff       lwr         upr     p adj
## Baja-Nunca   1.0784314 -1.178020  3.33488251 0.5970573
## Media-Nunca -0.4282353 -2.467702  1.61123093 0.9466082
## Alta-Nunca  -1.3708440 -3.460785  0.71909700 0.3216112
## Media-Baja  -1.5066667 -3.899585  0.88625204 0.3579360
## Alta-Baja   -2.4492754 -4.885356 -0.01319432 0.0482486
## Alta-Media  -0.9426087 -3.179200  1.29398280 0.6892205
# --- Boxplot para ANOVA
ggplot(datos, aes(x = frecuencia_educacion_ddhh,
                  y = satisfaccion_garantias_ddhh,
                  fill = frecuencia_educacion_ddhh)) +
  geom_boxplot() +
  labs(title="Satisfacción según Frecuencia de Educación en DDHH",
       x="Frecuencia de educación",
       y="Satisfacción") +
  theme_minimal()

# ============================================================
#   PRUEBA T
#   ¿Percepción cambia entre quienes han denunciado o no?
# ============================================================

t_denuncia <- t.test(percepcion_respeto_ddhh ~ ha_denunciado_vulneracion, data=datos)
t_denuncia
## 
##  Welch Two Sample t-test
## 
## data:  percepcion_respeto_ddhh by ha_denunciado_vulneracion
## t = 0.45234, df = 39.4, p-value = 0.6535
## alternative hypothesis: true difference in means between group No and group Sí is not equal to 0
## 95 percent confidence interval:
##  -0.9747147  1.5364862
## sample estimates:
## mean in group No mean in group Sí 
##         5.871795         5.590909
# --- Boxplot percepción según denuncia
ggplot(datos, aes(x = ha_denunciado_vulneracion,
                  y = percepcion_respeto_ddhh,
                  fill = ha_denunciado_vulneracion)) +
  geom_boxplot() +
  labs(title="Percepción del Respeto según Denuncias",
       x="¿Ha denunciado?",
       y="Percepción del respeto") +
  theme_minimal()

# ============================================================
#   REGRESIÓN LOGÍSTICA
#   Predicción de satisfacción (alta = 7–10)
# ============================================================

datos <- datos %>%
  mutate(satisfaccion_alta = ifelse(satisfaccion_garantias_ddhh >= 7, 1, 0))

modelo_logistico <- glm(
  satisfaccion_alta ~ participacion_actividades_ddhh +
    confianza_instituciones_ddhh +
    conocimiento_ddhh,
  data = datos,
  family = binomial
)

summary(modelo_logistico)
## 
## Call:
## glm(formula = satisfaccion_alta ~ participacion_actividades_ddhh + 
##     confianza_instituciones_ddhh + conocimiento_ddhh, family = binomial, 
##     data = datos)
## 
## Coefficients:
##                                   Estimate Std. Error z value Pr(>|z|)  
## (Intercept)                      -0.914688   0.518185  -1.765   0.0775 .
## participacion_actividades_ddhhSí  0.003221   0.468547   0.007   0.9945  
## confianza_instituciones_ddhh      0.090607   0.074438   1.217   0.2235  
## conocimiento_ddhh.L               0.648837   0.361662   1.794   0.0728 .
## conocimiento_ddhh.Q              -0.163921   0.370859  -0.442   0.6585  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 135.37  on 99  degrees of freedom
## Residual deviance: 130.64  on 95  degrees of freedom
## AIC: 140.64
## 
## Number of Fisher Scoring iterations: 4