PAQUETES ESTADISTICOS Y BASES DE DATOS

library(tidyverse) 
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.3     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2     
## ── 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(openxlsx) 
library(haven)
library(skimr)
library(readxl)
library(knitr)
library(rmarkdown) 

#choose.files()
fem=read_excel("C:\\Users\\DINDES08\\Desktop\\Informe feminicidio\\Base de datos feminicidio.xlsx", sheet="Hoja1",  range="A1:D391", col_names = TRUE)

kable(head(fem), format="markdown")
DEP AÑO INDICADOR VALOR
AMAZONAS 2022 Tasa de feminicidio NA
ÁNCASH 2022 Tasa de feminicidio 2.1540428
APURÍMAC 2022 Tasa de feminicidio 2.0077499
AREQUIPA 2022 Tasa de feminicidio 3.6971506
AYACUCHO 2022 Tasa de feminicidio 1.2138869
CAJAMARCA 2022 Tasa de feminicidio 0.5408124

ESTANDARIZACION DE DATOS

# Agrupa por departamento y realiza la estandarización para cada indicador
datos_estandarizados_a <- fem %>%
  group_by(AÑO,INDICADOR) %>%
  mutate(Valor_Estandarizado = scale(VALOR))

# suma ponderada con pesos

datos_estandarizados_x <- datos_estandarizados_a %>%
  group_by(DEP, AÑO) %>%
  summarise(Indice_Estandarizado = sum(case_when(
    INDICADOR == "Tasa de tentativa de feminicidio" ~ Valor_Estandarizado * 0.3,
    INDICADOR == "Tasa de feminicidio" ~ Valor_Estandarizado * 0.5,
    INDICADOR == "Porcentaje de violencia física y sexual" ~ Valor_Estandarizado * 0.2,
    TRUE ~ NA_real_
  ), na.rm = TRUE))
## `summarise()` has grouped output by 'DEP'. You can override using the `.groups`
## argument.
kable(head(datos_estandarizados_x), format = "markdown")
DEP AÑO Indice_Estandarizado
AMAZONAS 2018 -0.2893507
AMAZONAS 2019 0.4847282
AMAZONAS 2020 -0.1594801
AMAZONAS 2021 -0.2013738
AMAZONAS 2022 -0.0589191
APURÍMAC 2018 -0.1698185

GRAFICO TOTAL: TODOS LOS DEPARTAMENTOS

# Instala y carga la biblioteca 'ggplot2' si aún no lo has hecho
library(ggplot2)

# Crea un gráfico de líneas
ggplot(datos_estandarizados_x, aes(x = AÑO, y = Indice_Estandarizado, color = as.factor(DEP))) +
  geom_line(aes(group = DEP), size = 1) +
  geom_point(size = 2) +
  labs(title = "Índice Estandarizado por Año",
       x = "Año",
       y = "Índice Estandarizado") +
  scale_color_manual(values = rainbow(length(unique(datos_estandarizados_x$DEP)))) +  
  theme_minimal()

GRAFICO COMPARATIVO

# Departamentos que deseas comparar
departamentos_a_comparar <- c("MOQUEGUA", "MADREDEDIOS", "HUANCAVELICA","CAJAMARCA")

# Crear y filtrar los datos al mismo tiempo, luego graficar con escala de rojos
grafico <- ggplot(datos_estandarizados_x %>% filter(DEP %in% departamentos_a_comparar), 
       aes(x = AÑO, y = Indice_Estandarizado, color = DEP)) +
  geom_line(aes(group = DEP), size = 1, stat = "smooth", method = "loess") +
  geom_point(size = 2) +
  labs(title = "Índice Estandarizado por Año",
       x = "Año",
       y = "Índice Estandarizado") +
  scale_color_manual(values = c("#8B4513", "#FF0000", "#FFA500","skyblue")) +
  
  theme_minimal()

grafico
## `geom_smooth()` using formula = 'y ~ x'

GRAFICO POR DEPARTAMENTO

# Crea un gráfico de líneas para un departamento específico (por ejemplo, "Departamento_A")
ggplot(datos_estandarizados_x %>% filter(DEP == "ÁNCASH"), 
       aes(x = AÑO, y = Indice_Estandarizado)) +
  geom_line(size = 1) +
  geom_point(size = 2) +
  labs(title = "Índice Estandarizado por año - Áncash",
       x = "Año",
       y = "Índice Estandarizado") +
  theme_minimal()

grafico1 <- ggplot(datos_estandarizados_x %>% filter(DEP == "ÁNCASH"), 
       aes(x = AÑO, y = Indice_Estandarizado)) +
  geom_smooth(size = 1, color = "#FF6666", method = "loess", se = FALSE) +  # Línea suavizada
  geom_point(size = 2, color = "#FF6666") +  # Puntos
  labs(title = "Índice Estandarizado por departamento - Áncash",
       x = "Año",
       y = "Índice Estandarizado") +
  theme_minimal()
grafico1
## `geom_smooth()` using formula = 'y ~ x'

# GRAFICO COMPARATIVO DEPARTAMENTOS SEGUN AÑO

grafico2<-ggplot(datos_estandarizados_x %>% filter(AÑO == 2019) %>%
         arrange(desc(Indice_Estandarizado)), 
       aes(x = reorder(DEP, -Indice_Estandarizado), y = Indice_Estandarizado)) +
  geom_bar(stat = "identity", fill = "#FF6666") +
  labs(title = "Índice de vulnerabilidad de la mujer joven en el Perú por Departamento - Año 2019",
       x = "Departamento",
       y = "Índice Estandarizado") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

grafico2

GUARDAR IMAGEN

# Guardar el gráfico en formato PNG
ruta <- "C:/Users/DINDES08/Desktop/Informe feminicidio/"
nombre_archivo <- "grafico.jpg"

# Combinar la ruta y el nombre del archivo utilizando file.path
ruta_completa <- file.path(ruta, nombre_archivo)

# Guardar el gráfico en formato PNG en la ubicación especificada
ggsave(ruta_completa, plot = grafico1, width = 8, height = 6, units = "in")
## `geom_smooth()` using formula = 'y ~ x'