1. Introduccion

El presente informe tiene como objetivo realizar un análisis exploratorio de datos (EDA). completo de un conjunto de datos relacionados con crímenes, utilizando el lenguaje de programación R. El dataset incluye las siguientes variables: date, time, crime_type, city, state, location_description, victim_age, victim_gender y victim_race.

A lo largo del documento se aplican diversas técnicas estadísticas y visualizaciones para obtener información relevante y patrones significativos.

Entre los principales análisis realizados se incluyen:

Análisis Resumen edad Crimen frecuente por ubicacion Edad promedio por crimen Ubicacion más crimenes por fecha

Gráficos Crimenes por tipo Edad_por_genero Tendencia_crimen

Este análisis busca no solo describir el comportamiento de los datos, sino también identificar tendencias que puedan ser útiles para la toma de decisiones o el diseño de políticas públicas orientadas a la seguridad.

2. Librerias

3. Carga de Datos

# Ruta donde se almacena la data 
ruta_archivo<- read_csv("C:/TD/R/datos_crimen.csv")
glimpse(ruta_archivo)
## Rows: 1,000
## Columns: 10
## $ id                   <dbl> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15…
## $ date                 <date> 2022-09-09, 2022-07-10, 2024-12-31, 2024-04-12, …
## $ time                 <time> 18:58:57, 12:10:59, 09:26:12, 23:17:28, 04:49:39…
## $ crime_type           <chr> "Homicide", "Assault", "Burglary", "Vandalism", "…
## $ city                 <chr> "Philadelphia", "Phoenix", "San Antonio", "Philad…
## $ state                <chr> "PA", "AZ", "TX", "PA", "TX", "IL", "PA", "TX", "…
## $ location_description <chr> "9916 Broadway", "6853 Oak St", "3760 Maple Ave",…
## $ victim_age           <dbl> 34, 13, 23, 36, 26, 70, 48, 47, 28, 44, 29, 20, 3…
## $ victim_gender        <chr> "Male", "Female", "Male", "Other", "Other", "Non-…
## $ victim_race          <chr> "Other", "Black", "Asian", "Asian", "Other", "Oth…

3. Limpieza y Transformación

# Cargar datos desde un archivo CSV
# ---------------------------------------
# @param ruta_archivo [str] Ruta del archivo CSV
# @return [data.frame] DataFrame con los datos cargados
cargar_datos <- function(ruta_archivo) {
  read_csv(ruta_archivo, show_col_types = FALSE)
}
# Limpiar y transformar datos
# ---------------------------------------
# @param datos [data.frame] Datos crudos cargados
# @return [data.frame] Datos transformados
limpiar_datos <- function(datos) {
  datos %>%
    mutate(
      date = as.Date(date),
      time = as_hms(time),
      victim_age = as.numeric(victim_age)
    )
}

4. Análisis Estadístico

4.1 Calcular estadisticas de edad

# Calcular estadisticas de edad
# ---------------------------------------
# @param datos [data.frame] Datos limpios
# @return [data.frame] Media y desviación estándar de edad
resumen_edad <- function(datos) {
  datos %>%
    summarise(
      media_edad = mean(victim_age, na.rm = TRUE),
      sd_edad = sd(victim_age, na.rm = TRUE)
    )
}

4.2 Crimen Más Frecuente por Ubicación

# Crimen Más Frecuente por Ubicación
# ---------------------------------------
# @param datos [data.frame] Datos limpios
# @return [data.frame] Crimen Más Frecuente por Ubicación
crimen_frecuente_por_ubicacion <- function(datos) {
  datos %>%
    count(location_description, crime_type, sort = TRUE) %>%
    group_by(location_description) %>%
    slice_max(n, n = 1)
}

4.3 Edad Promedio por Tipo de Crimen

#Edad promedio por tipo de crimen
# ---------------------------------------
# @param datos [data.frame] Datos limpios
# @return [data.frame] Edad media por tipo de crimen
edad_promedio_por_crimen <- function(datos) {
  datos %>%
    group_by(crime_type) %>%
    summarise(media_edad = mean(victim_age, na.rm = TRUE)) %>%
    arrange(desc(media_edad))
}

4.4 Lugar con más Crímenes por Fecha

# Lugar con más Crímenes por Fecha
# ---------------------------------------
# @param datos [data.frame] Datos limpios
# @return [data.frame] Ubicación con más crimenes por fecha
ubicacion_mas_crimenes_por_fecha <- function(datos) {
  datos %>%
    group_by(date, location_description) %>%
    summarise(total = n(), .groups = "drop") %>%
    arrange(desc(total)) %>%
    group_by(date) %>%
    slice_max(total, n = 1)
}

4.5 Gráfico de crimenes por tipo

# Gráfico de crimenes por tipo
graficar_crimenes_por_tipo <- function(datos) {
  ggplot(datos %>% count(crime_type), aes(x = reorder(crime_type, n), y = n)) +
    geom_col(fill = "steelblue") +
    coord_flip() +
    labs(title = "Total de crimenes por tipo", x = "Tipo de crimen", y = "Cantidad") +
    theme_minimal()
}

4.6 Función: Boxplot de edad por género

# Función: Boxplot de edad por género
graficar_edad_por_genero <- function(datos) {
  ggplot(datos, aes(x = victim_gender, y = victim_age, fill = victim_gender)) +
    geom_boxplot() +
    labs(title = "Distribucion de edad por genero", x = "Genero", y = "Edad") +
    theme_minimal()
}

4.7 Tendencia de crimen por raza y tipo en el tiempo

# Tendencia de crimen por raza y tipo en el tiempo
graficar_tendencia_crimen <- function(datos) {
  datos %>%
    mutate(mes = floor_date(date, "month")) %>%
    count(mes, crime_type, victim_race) %>%
    ggplot(aes(x = mes, y = n, color = victim_race)) +
    geom_line(linewidth = 1) +
    facet_wrap(~crime_type, scales = "free_y") +
    labs(title = "Tendencia mensual de crimenes por tipo y raza",
         x = "Mes",
         y = "Numero de crimenes") +
    theme_minimal()
}

5. Visualizaciones

5.1. Visualizaciones

# Ruta del archivo
ruta_csv <- "C:/TD/R/datos_crimen.csv"

5.1. Datos

# Cargar y limpiar datos
datos <- cargar_datos(ruta_csv)
datos_limpios <- limpiar_datos(datos)

5.2. Datos resumen_edad

print(resumen_edad(datos_limpios))
## # A tibble: 1 × 2
##   media_edad sd_edad
##        <dbl>   <dbl>
## 1       52.2    22.9

5.3. Datos crimen_frecuente_por_ubicacion

print(crimen_frecuente_por_ubicacion(datos_limpios))
## # A tibble: 999 × 3
## # Groups:   location_description [988]
##    location_description crime_type       n
##    <chr>                <chr>        <int>
##  1 100 Oak St           Robbery          1
##  2 1001 Maple Ave       Drug Offense     1
##  3 1013 Broadway        Assault          1
##  4 1027 Elm St          Burglary         1
##  5 105 Elm St           Burglary         1
##  6 105 Pine St          Arson            1
##  7 1061 Pine St         Robbery          1
##  8 1065 Oak St          Theft            1
##  9 1066 Maple Ave       Homicide         1
## 10 1074 Broadway        Drug Offense     1
## # ℹ 989 more rows

5.3. Datos edad_promedio_por_crimen

print(edad_promedio_por_crimen(datos_limpios))
## # A tibble: 10 × 2
##    crime_type        media_edad
##    <chr>                  <dbl>
##  1 Vandalism               56.4
##  2 Theft                   53.7
##  3 Assault                 52.5
##  4 Fraud                   52.5
##  5 Arson                   52.1
##  6 Burglary                52.1
##  7 Robbery                 52.0
##  8 Drug Offense            51.0
##  9 Domestic Violence       50.8
## 10 Homicide                49.5

5.4. Datos ubicacion_mas_crimenes_por_fecha

print(ubicacion_mas_crimenes_por_fecha(datos_limpios))
## # A tibble: 1,000 × 3
## # Groups:   date [772]
##    date       location_description total
##    <date>     <chr>                <int>
##  1 2020-07-31 960 Pine St              1
##  2 2020-08-01 5798 Oak St              1
##  3 2020-08-01 6221 Elm St              1
##  4 2020-08-04 7402 Broadway            1
##  5 2020-08-05 5145 Broadway            1
##  6 2020-08-06 7584 Oak St              1
##  7 2020-08-08 4959 Pine St             1
##  8 2020-08-10 2126 Oak St              1
##  9 2020-08-10 464 Oak St               1
## 10 2020-08-15 2992 Maple Ave           1
## # ℹ 990 more rows

5.5. Gráficos

# =======================================
# SCRIPT PRINCIPAL
# =======================================

# Ruta del archivo
ruta_csv <- "C:/TD/R/datos_crimen.csv"

# Cargar y limpiar datos
datos <- cargar_datos(ruta_csv)
datos_limpios <- limpiar_datos(datos)

# Análisis
print(resumen_edad(datos_limpios))
## # A tibble: 1 × 2
##   media_edad sd_edad
##        <dbl>   <dbl>
## 1       52.2    22.9
print(crimen_frecuente_por_ubicacion(datos_limpios))
## # A tibble: 999 × 3
## # Groups:   location_description [988]
##    location_description crime_type       n
##    <chr>                <chr>        <int>
##  1 100 Oak St           Robbery          1
##  2 1001 Maple Ave       Drug Offense     1
##  3 1013 Broadway        Assault          1
##  4 1027 Elm St          Burglary         1
##  5 105 Elm St           Burglary         1
##  6 105 Pine St          Arson            1
##  7 1061 Pine St         Robbery          1
##  8 1065 Oak St          Theft            1
##  9 1066 Maple Ave       Homicide         1
## 10 1074 Broadway        Drug Offense     1
## # ℹ 989 more rows
print(edad_promedio_por_crimen(datos_limpios))
## # A tibble: 10 × 2
##    crime_type        media_edad
##    <chr>                  <dbl>
##  1 Vandalism               56.4
##  2 Theft                   53.7
##  3 Assault                 52.5
##  4 Fraud                   52.5
##  5 Arson                   52.1
##  6 Burglary                52.1
##  7 Robbery                 52.0
##  8 Drug Offense            51.0
##  9 Domestic Violence       50.8
## 10 Homicide                49.5
print(ubicacion_mas_crimenes_por_fecha(datos_limpios))
## # A tibble: 1,000 × 3
## # Groups:   date [772]
##    date       location_description total
##    <date>     <chr>                <int>
##  1 2020-07-31 960 Pine St              1
##  2 2020-08-01 5798 Oak St              1
##  3 2020-08-01 6221 Elm St              1
##  4 2020-08-04 7402 Broadway            1
##  5 2020-08-05 5145 Broadway            1
##  6 2020-08-06 7584 Oak St              1
##  7 2020-08-08 4959 Pine St             1
##  8 2020-08-10 2126 Oak St              1
##  9 2020-08-10 464 Oak St               1
## 10 2020-08-15 2992 Maple Ave           1
## # ℹ 990 more rows
# Gráficos
graficar_crimenes_por_tipo(datos_limpios)

graficar_edad_por_genero(datos_limpios)

graficar_tendencia_crimen(datos_limpios)