#AVISO IMPORANTE!

# Originalmente, la variable subtipo de líquidos era de naturaleza cualitativa nominal, ya que solo listaba nombres de fluidos sin un orden inherente. Para enriquecer el análisis de seguridad, se realizó una transformación a variable ordinal aplicando un criterio de volatilidad y riesgo de explosión.

#Se reclasificaron los fluidos en tres niveles jerárquicos:
#Nivel 1: Bajo riesgo
#Nivel 2: Medio riesgo
#Nivel 3: Alto riesgo

1 Cargar datos

datos <- read.csv("database-_1_.csv")
zona<-datos$Liquid.Subtype

2 Tabla de frecuencia

datos_liquidos <- datos %>%
  mutate(Subtipo_Clean = case_when(
    is.na(Liquid.Subtype) | Liquid.Subtype == "" ~ "CRUDO / CO2",
    grepl("DIESEL", Liquid.Subtype) ~ "DIESEL / JET FUEL / KEROSENE",
    grepl("GASOLINE", Liquid.Subtype) ~ "GASOLINA",
    grepl("LPG", Liquid.Subtype) ~ "GASES LICUADOS",
    grepl("OTHER HVL", Liquid.Subtype) ~ "LÍQUIDO AlTAMENTE VOLÁTIL",
    TRUE ~ "AMONÍACO, BIODIESEL" 
  )) %>%
  mutate(Nivel_Riesgo = case_when(
    Subtipo_Clean == "CRUDO / CO2" ~ 1,
    Subtipo_Clean %in% c("GASOLINA", "DIESEL / JET FUEL / KEROSENE", "AMONÍACO, BIODIESEL") ~ 2,
    Subtipo_Clean %in% c("GASES LICUADOS", "LÍQUIDO AlTAMENTE VOLÁTIL") ~ 3,
    
    TRUE ~ 0
  ))
TDF_agrupada <- datos_liquidos %>%
  count(Nivel_Riesgo, Subtipo_Clean, name = "ni") %>%
  arrange(Nivel_Riesgo, desc(ni)) 
ni_total <- sum(TDF_agrupada$ni)
TDF_agrupada$hi <- (TDF_agrupada$ni / ni_total) * 100
TDF_agrupada$hi <- sprintf("%.2f", round(TDF_agrupada$hi, 2))
Sumatoria <- data.frame(
  Nivel_Riesgo = "",
  Subtipo_Clean = "TOTAL",
  ni = ni_total,
  hi = "100.00"
)

TDF_final <- rbind(TDF_agrupada, Sumatoria)
colnames(TDF_final) <- c("Nivel Riesgo", "Tipo de Subtipo de Líquido", "ni", "hi (%)")
kable(TDF_final, align = 'c', 
      caption = "Tabla 1: Frecuencia de Líquidos  por Riesgo") %>%
  kable_styling(full_width = FALSE, position = "center", 
                bootstrap_options = c("striped", "hover", "condensed")) %>%
  row_spec(nrow(TDF_final), bold = TRUE, background = "#f2f2f2") %>%
  row_spec(which(TDF_final$`Nivel Riesgo` == 3), bold = TRUE)
Tabla 1: Frecuencia de Líquidos por Riesgo
Nivel Riesgo Tipo de Subtipo de Líquido ni hi (%)
1 CRUDO / CO2 1446 51.74
2 DIESEL / JET FUEL / KEROSENE 410 14.67
2 GASOLINA 376 13.45
2 AMONÍACO, BIODIESEL 204 7.30
3 GASES LICUADOS 188 6.73
3 LÍQUIDO AlTAMENTE VOLÁTIL 171 6.12
TOTAL 2795 100.00

3 Frecuencia absoluta local de Accidentes según la Volatilidad del Líquido

datos_grafico <- datos %>%
  mutate(Subtipo_Clean = case_when(
    is.na(Liquid.Subtype) | Liquid.Subtype == "" ~ "CRUDO / CO2 ",
    grepl("DIESEL", Liquid.Subtype) ~ "DIESEL / JET FUEL / KEROSENE",
    grepl("GASOLINE", Liquid.Subtype) ~ "GASOLINA",
    grepl("LPG", Liquid.Subtype) ~ "AMONÍACO, BIODIESEL",
    grepl("OTHER HVL", Liquid.Subtype) ~ "LÍQUIDO ALTAMENTE VOLÁTIL",
    TRUE ~ "GASES LICUADOS"
  )) %>%
  mutate(Nivel_Riesgo = case_when(
    Subtipo_Clean == "CRUDO / CO2 " ~ "1. Bajo",
    Subtipo_Clean %in% c("GASOLINA", "DIESEL / JET FUEL / KEROSENE", "AMONÍACO, BIODIESEL") ~ "2. Medio",
    Subtipo_Clean %in% c("GASES LICUADOS", "LÍQUIDO ALTAMENTE VOLÁTIL") ~ "3. Alto",
    TRUE ~ "0. Desconocido"
  )) %>%
  count(Nivel_Riesgo, Subtipo_Clean, name = "ni")
ggplot(datos_grafico, aes(x = reorder(Subtipo_Clean, -ni), y = ni, fill = Nivel_Riesgo)) + 
  geom_bar(stat = "identity", width = 0.75, color = "black") + 
  scale_fill_manual(values = c(
    "1. Bajo" = "#AED6F1",  
    "2. Medio" = "#3498DB",  
    "3. Alto" = "#154360"    
  )) +
  
  labs(
    title = "Gráfica N1: Clasificación por Nivel de Riesgo (Escala de Volatilidad)",
    x = "Subtipo de líquido",
    y = "Cantidad",
    fill = "Nivel de Riesgo"
  ) +
  
  theme_light() +
  theme(
    axis.text.x = element_text(angle = 45, hjust = 1, color = "black"),
    legend.position = "top"
  )

4 Frecuencia Absoluta Global de Accidentes por Subtipo de Fluido

datos_grafico_global <- datos %>%
  mutate(Subtipo_Clean = case_when(
    is.na(Liquid.Subtype) | Liquid.Subtype == "" ~ "CRUDO / CO2",
    grepl("DIESEL", Liquid.Subtype) ~ "DIESEL / JET FUEL / KEROSENE",
    grepl("GASOLINE", Liquid.Subtype) ~ "GASOLINA",
    grepl("LPG", Liquid.Subtype) ~ "AMONÍACO, BIODIESEL",
    grepl("OTHER HVL", Liquid.Subtype) ~ "LÍQUIDO ALTAMENTE VOLÁTIL",
    TRUE ~ "GASES LICUADOS"
  )) %>%
  mutate(Nivel_Riesgo = case_when(
    Subtipo_Clean == "CRUDO / CO2" ~ "1. Bajo",
    Subtipo_Clean %in% c("GASOLINA", "DIESEL / JET FUEL / KEROSENE", "AMONÍACO, BIODIESE") ~ "2. Medio",
    Subtipo_Clean %in% c("GASES LICUADOS","LÍQUIDO ALTAMENTE VOLÁTIL") ~ "3. Alto",
    TRUE ~ "0. Desconocido"
  )) %>%
  count(Nivel_Riesgo, Subtipo_Clean, name = "ni")
ggplot(datos_grafico_global, aes(x = reorder(Subtipo_Clean, -ni), y = ni, fill = Nivel_Riesgo)) + 
  
  geom_bar(stat = "identity", width = 0.7, color = "black") + 
  scale_fill_manual(values = c(
    "1. Bajo" = "#AED6F1",   
    "2. Medio" = "#3498DB",  
    "3. Alto" = "#154360"    
  )) +
  scale_y_continuous(
    limits = c(0, 2795),        
    breaks = seq(0, 2795, 500)  
  ) +
  
  labs(
    title = "Gráfica N2: Distribución Global de Accidentes",
    x = "Subtipo de Líquido",
    y = "Cantidad",
    fill = "Nivel de Riesgo"
  ) +
  
  theme_light() +
  theme(
    axis.text.x = element_text(angle = 45, hjust = 1, color = "black"),
    legend.position = "top"
  )

5 Porcentaje global de Accidentes por Subtipo de Líquido

datos_hi_local <- datos %>%
  mutate(Subtipo_Clean = case_when(
    is.na(Liquid.Subtype) | Liquid.Subtype == "" ~ "CRUDO / CO2",
    grepl("DIESEL", Liquid.Subtype) ~ "DIESEL / JET FUEL / KEROSENE",
    grepl("GASOLINE", Liquid.Subtype) ~ "GASOLINA",
    grepl("LPG", Liquid.Subtype) ~ "AMONÍACO, BIODIESEL",
    grepl("OTHER HVL", Liquid.Subtype) ~ "LÍQUIDO ALTAMENTE VOLÁTIL",
    TRUE ~ "GASES LICUADOS"
  )) %>%
  mutate(Nivel_Riesgo = case_when(
    Subtipo_Clean == "CRUDO / CO2" ~ "1. Bajo",
    Subtipo_Clean %in% c("GASOLINA", "DIESEL / JET FUEL / KEROSENE", "AMONÍACO, BIODIESEL") ~ "2. Medio",
    Subtipo_Clean %in% c("GASES LICUADOS", "LÍQUIDO ALTAMENTE VOLÁTIL") ~ "3. Alto",
    TRUE ~ "0. Desconocido"
  )) %>%
  count(Nivel_Riesgo, Subtipo_Clean, name = "ni") %>%
  mutate(hi_pct = (ni / sum(ni)) * 100)
ggplot(datos_hi_local, aes(x = reorder(Subtipo_Clean, -hi_pct), y = hi_pct, fill = Nivel_Riesgo)) +
  geom_bar(stat = "identity", width = 0.7, color = "black") +
  scale_fill_manual(values = c(
    "1. Bajo" = "#AED6F1",
    "2. Medio" = "#3498DB",  
    "3. Alto" = "#154360"    
  )) +
  scale_y_continuous(limits = c(0, 100), breaks = seq(0, 100, by = 20)) +
  
  labs(
    title = "Gráfica 3: Porcentaje global de Accidentes por Nivel de Riesgo",
    x = "Subtipo de Líquido",
    y = "Porcentaje (%)",
    fill = "Nivel de Riesgo"
  ) +
  
  theme_classic() +
  theme(
    axis.text.x = element_text(angle = 45, hjust = 1, color = "black"),
    legend.position = "top"
  )

6 Porcentaje local de Incidentes Clasificada por Volatilidad del Material

datos_hi_local <- datos %>%
  mutate(Subtipo_Clean = case_when(
    is.na(Liquid.Subtype) | Liquid.Subtype == "" ~ "CRUDO / CO2",
    grepl("DIESEL", Liquid.Subtype) ~ "DIESEL / JET FUEL / KEROSENE",
    grepl("GASOLINE", Liquid.Subtype) ~ "GASOLINA",
    grepl("LPG", Liquid.Subtype) ~ "AMONÍACO, BIODIESEL",
    grepl("OTHER HVL", Liquid.Subtype) ~ "LÍQUIDO ALTAMENTE VOLÁTIL",
    TRUE ~ "GASES LICUADOS"
  )) %>%
  # 1. Agregamos la clasificación Ordinal
  mutate(Nivel_Riesgo = case_when(
    Subtipo_Clean == "CRUDO / CO2" ~ "1. Bajo",
    Subtipo_Clean %in% c("GASOLINA", "DIESEL / JET FUEL / KEROSENE", "AMONÍACO, BIODIESEL") ~ "2. Medio",
    Subtipo_Clean %in% c("GASES LICUADOS", "LÍQUIDO ALTAMENTE VOLÁTIL") ~ "3. Alto",
    TRUE ~ "0. Desconocido"
  )) %>%
  count(Nivel_Riesgo, Subtipo_Clean, name = "ni") %>%
  mutate(hi_pct = (ni / sum(ni)) * 100) 
ggplot(datos_hi_local, aes(x = reorder(Subtipo_Clean, -hi_pct), y = hi_pct, fill = Nivel_Riesgo)) +
  geom_bar(stat = "identity", width = 0.7, color = "black") +
  scale_fill_manual(values = c(
    "1. Bajo" = "#AED6F1",   
    "2. Medio" = "#3498DB",  
    "3. Alto" = "#154360"    
  )) +
  
  labs(
    title = "Gráfica 4: Porcentaje local de Accidentes por subtipo de liquidos",
    x = "Subtipo de Líquido",
    y = "Porcentaje (%)",
    fill = "Nivel de Riesgo"
  ) +
  
  theme_classic() +
  
  # Ajustes visuales
  theme(
    axis.text.x = element_text(angle = 45, hjust = 1),
    legend.position = "top"
  )

7 Diagrama Circular

datos_grafico <- datos %>%
  mutate(Subtipo_Clean = case_when(
    is.na(Liquid.Subtype) | Liquid.Subtype == "" ~ "CRUDO / CO2",
    grepl("DIESEL", Liquid.Subtype) ~ "DIESEL / JET FUEL / KEROSENE",
    grepl("GASOLINE", Liquid.Subtype) ~ "GASOLINA",
    grepl("LPG", Liquid.Subtype) ~ "AMONÍACO, BIODIESEL",
    grepl("OTHER HVL", Liquid.Subtype) ~ "LÍQUIDO ALTAMENTE VOLÁTIL",
    TRUE ~ "GASES LICUADOS"
  )) %>%
  count(Subtipo_Clean, name = "ni") %>%
  mutate(hi_pct = round((ni / sum(ni)) * 100, 1)) %>%
  mutate(Subtipo_Clean = factor(Subtipo_Clean, levels = c(
    "AMONÍACO, BIODIESEL", "LÍQUIDO ALTAMENTE VOLÁTIL",                 
    "GASOLINA", "DIESEL / JET FUEL / KEROSENE", "GASES LICUADOS",
    "CRUDO / CO2"                 
  )))
colores_riesgo_map <- c(
  # Nivel 3: Alto (Azul Oscuro)
  "AMONÍACO, BIODIESEL" = "#154360",
  "LÍQUIDO ALTAMENTE VOLÁTIL" = "#154360",
  
  # Nivel 2: Medio (Azul Rey)
  "GASOLINA" = "#3498DB",
  "DIESEL / JET FUEL / KEROSENE" = "#3498DB",
  "GASES LICUADOS" = "#3498DB",
  
  # Nivel 1: Bajo (Azul Cielo)
  "CRUDO / CO2" = "#AED6F1"
)
ggplot(datos_grafico, aes(x = "", y = hi_pct, fill = Subtipo_Clean)) +
  geom_bar(stat = "identity", width = 1, color = "white", size = 1) +
  coord_polar("y", start = 0) +
  geom_text(aes(label = paste0(hi_pct, "%")), 
            position = position_stack(vjust = 0.5), 
            color = "white", size = 3.5, fontface = "bold") +
  scale_fill_manual(values = colores_riesgo_map) +
  
  labs(
    title =    " Gráfica 5: Distribución de diagrama circular por     
    Subtipo Líquido",
    fill = "Subtipo de Líquido"
  ) +
  
  theme_void() +
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold", margin = margin(b = 10)),
    plot.subtitle = element_text(hjust = 0.5, size = 10, color = "gray30"),
    legend.position = "right", 
    legend.text = element_text(size = 9)
  )
## Warning in geom_bar(stat = "identity", width = 1, color = "white", size = 1):
## Ignoring unknown parameters: `size`

8 Indicadores Estadístico

# --- TU CÓDIGO ORIGINAL (Cálculo de la Moda) ---
variable_limpia <- trimws(toupper(na.omit(datos$Liquid.Subtype)))
variable_limpia <- variable_limpia[variable_limpia != ""]
tabla_frecuencia <- table(variable_limpia)

# Identificamos el nombre del más repetido
mas_repetido <- names(tabla_frecuencia)[which.max(tabla_frecuencia)]
cantidad <- max(tabla_frecuencia)
total_validos <- sum(tabla_frecuencia)
porcentaje <- round((cantidad / total_validos) * 100, 2)

# Usamos la misma lógica que en tus gráficos anteriores
riesgo_moda <- case_when(
  # Nivel 1: Crudos
  mas_repetido == "CRUDE OIL" | grepl("CO2", mas_repetido) ~ "1. Bajo (Crudos/Pesados)",
  
  # Nivel 3: Gases/HVL (Los buscamos primero por ser críticos)
  grepl("LPG", mas_repetido) | grepl("HVL", mas_repetido) | grepl("PROPANE", mas_repetido) | grepl("AMMONIA", mas_repetido) ~ "3. Alto (Gases/HVL)",
  
  # Nivel 2: Todo lo demás (Refinados como Gasolina, Diesel, etc.)
  TRUE ~ "2. Medio (Refinados/Inflamables)"
)

# --- IMPRESIÓN DE RESULTADOS ---
cat("--- Estadísticas de la Moda (Liquid.Subtype) ---\n")
## --- Estadísticas de la Moda (Liquid.Subtype) ---
cat("El subtipo más frecuente es:", mas_repetido, "\n")
## El subtipo más frecuente es: DIESEL, FUEL OIL, KEROSENE, JET FUEL
cat("Nivel de Riesgo asociado:   ", riesgo_moda, "\n")
## Nivel de Riesgo asociado:    2. Medio (Refinados/Inflamables)
cat("Cantidad de ocurrencias:    ", cantidad, "\n")
## Cantidad de ocurrencias:     408
cat("Porcentaje del total:       ", porcentaje, "%\n")
## Porcentaje del total:        30.24 %

9 Conclusión

#El análisis de la variable subtipo de líquidos indica que la categoría agrupada de combustibles refinados pesados y medios (Diesel, Fuel Oil, Kerosene, Jet Fuel) es la fuente más frecuente de incidentes, representando el 30.24% del total (408 casos).

#Sin embargo, es importante notar que la Gasolina (Non-Ethanol) sigue muy de cerca en segundo lugar con 376 casos (aprox. 27%). Esto sugiere que la mayoría de los accidentes (cerca del 57%) se concentran en estos dos grandes grupos de combustibles refinados.