library(knitr)
library(kableExtra)
library(dplyr)
## 
## Adjuntando el paquete: 'dplyr'
## The following object is masked from 'package:kableExtra':
## 
##     group_rows
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
# --- PASO 1: Limpieza y Agrupación ---
datos_liquidos <- datos %>%
  # 1. Rellenar vacíos (Crudo) y limpiar nombres largos
  mutate(Subtipo_Clean = case_when(
    is.na(Liquid.Subtype) | Liquid.Subtype == "" ~ "CRUDO / CO2 (Sin Subtipo)",
    grepl("DIESEL", Liquid.Subtype) ~ "DIESEL / JET FUEL / KEROSENE",
    grepl("GASOLINE", Liquid.Subtype) ~ "GASOLINA",
    grepl("LPG", Liquid.Subtype) ~ "LPG / NGL (Gases Licuados)",
    grepl("OTHER HVL", Liquid.Subtype) ~ "OTROS HVL",
    TRUE ~ "OTROS (Mezclas, Amoníaco, Biodiesel)" # Agrupa todo lo demás
  ))
TDF_agrupada <- datos_liquidos %>%
  count(Subtipo_Clean, name = "ni") %>%
  arrange(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(
  Subtipo_Clean = "TOTAL",
  ni = ni_total,
  hi = "100.00"
)

TDF_final <- rbind(TDF_agrupada, Sumatoria)
colnames(TDF_final) <- c("Tipo de Líquido (Agrupado)", "ni", "hi (%)")

# --- PASO 5: Visualizar ---
kable(TDF_final, align = 'c', 
      caption = "Tabla 1: Frecuencia de Líquidos") %>%
  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$`Tipo de Líquido (Agrupado)` == "OTROS (Mezclas, Amoníaco, Biodiesel)"), 
           italic = TRUE, color = "#555555")
Tabla 1: Frecuencia de Líquidos
Tipo de Líquido (Agrupado) ni hi (%)
CRUDO / CO2 (Sin Subtipo) 1446 51.74
DIESEL / JET FUEL / KEROSENE 410 14.67
GASOLINA 376 13.45
OTROS (Mezclas, Amoníaco, Biodiesel) 204 7.30
LPG / NGL (Gases Licuados) 188 6.73
OTROS HVL 171 6.12
TOTAL 2795 100.00
#barra local
library(ggplot2)
library(dplyr)

# --- PASO 1: Preparar los datos ---
datos_grafico <- datos %>%
  mutate(Subtipo_Clean = case_when(
    is.na(Liquid.Subtype) | Liquid.Subtype == "" ~ "CRUDO / CO2 (Sin Subtipo)",
    grepl("DIESEL", Liquid.Subtype) ~ "DIESEL / JET FUEL / KEROSENE",
    grepl("GASOLINE", Liquid.Subtype) ~ "GASOLINA",
    grepl("LPG", Liquid.Subtype) ~ "LPG / NGL",
    grepl("OTHER HVL", Liquid.Subtype) ~ "OTROS HVL",
    TRUE ~ "OTROS (Mezclas, etc.)"
  )) %>%
  count(Subtipo_Clean, name = "ni")
ggplot(datos_grafico, aes(x = reorder(Subtipo_Clean, ni), y = ni)) + 
  geom_bar(stat = "identity", fill = "skyblue", width = 0.7) +
  
  labs(
    title = "Gráfica 1: Número de Accidentes",
    x = "Subtipo de Líquido",
    y = "Número de Accidentes"
  ) +
  theme_classic() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

library(ggplot2)
library(dplyr)
datos_grafico <- datos %>%
  mutate(Subtipo_Clean = case_when(
    is.na(Liquid.Subtype) | Liquid.Subtype == "" ~ "CRUDO / CO2 (Sin Subtipo)",
    grepl("DIESEL", Liquid.Subtype) ~ "DIESEL / JET FUEL / KEROSENE",
    grepl("GASOLINE", Liquid.Subtype) ~ "GASOLINA",
    grepl("LPG", Liquid.Subtype) ~ "LPG / NGL",
    grepl("OTHER HVL", Liquid.Subtype) ~ "OTROS HVL",
    TRUE ~ "OTROS (Mezclas, etc.)"
  )) %>%
  count(Subtipo_Clean, name = "ni")
ggplot(datos_grafico, aes(x = reorder(Subtipo_Clean, ni), y = ni)) + 
  
  geom_bar(stat = "identity", fill = "skyblue", width = 0.7) +
  scale_y_continuous(limits = c(0, 2795), breaks = c(0, 1000, 2000, 2795)) +
  labs(
    title = "Gráfica 2: Número de Accidentes",
    x = "Subtipo de Líquido",
    y = "Número de Accidentes"
  ) +
  theme_classic() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

# barra hi general
library(ggplot2)
library(dplyr)
datos_hi_local <- datos %>%
  mutate(Subtipo_Clean = case_when(
    is.na(Liquid.Subtype) | Liquid.Subtype == "" ~ "CRUDO / CO2 (Sin Subtipo)",
    grepl("DIESEL", Liquid.Subtype) ~ "DIESEL / JET FUEL / KEROSENE",
    grepl("GASOLINE", Liquid.Subtype) ~ "GASOLINA",
    grepl("LPG", Liquid.Subtype) ~ "LPG / NGL",
    grepl("OTHER HVL", Liquid.Subtype) ~ "OTROS HVL",
    TRUE ~ "OTROS (Mezclas, etc.)"
  )) %>%
  count(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)) +
  
  geom_bar(stat = "identity", fill = "skyblue", width = 0.7) +
  scale_y_continuous(limits = c(0, 100), breaks = seq(0, 100, by = 20)) +
  labs(
    title = "Gráfica 3: Número de Accidentes por porcentaje",
    x = "Subtipo de Líquido",
    y = "Porcentaje (%)"
  ) +
  
  theme_classic() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

library(ggplot2)
library(dplyr)

# --- PASO 1: Calcular Porcentajes Individuales (hi) ---
datos_hi_local <- datos %>%
  mutate(Subtipo_Clean = case_when(
    is.na(Liquid.Subtype) | Liquid.Subtype == "" ~ "CRUDO / CO2 (Sin Subtipo)",
    grepl("DIESEL", Liquid.Subtype) ~ "DIESEL / JET FUEL / KEROSENE",
    grepl("GASOLINE", Liquid.Subtype) ~ "GASOLINA",
    grepl("LPG", Liquid.Subtype) ~ "LPG / NGL",
    grepl("OTHER HVL", Liquid.Subtype) ~ "OTROS HVL",
    TRUE ~ "OTROS (Mezclas, etc.)"
  )) %>%
  count(Subtipo_Clean, name = "ni") %>%
  # Calculamos el porcentaje individual de cada uno
  mutate(hi_pct = (ni / sum(ni)) * 100) 

# --- PASO 2: Gráfica hi Local ---
ggplot(datos_hi_local, aes(x = reorder(Subtipo_Clean, -hi_pct), y = hi_pct)) +
  
  geom_bar(stat = "identity", fill = "skyblue", width = 0.7) +
  
  labs(
    title = "Gráfica 5: Cantidad de Accidentes por subtipo de liquidos", 
    x = "Subtipo de Líquido",
    y = "Porcentaje (%)"
  ) +
  
  theme_classic() +
  
  # Rotar texto del eje X
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

#diagrama circular
library(ggplot2)
library(dplyr)
datos_grafico <- datos %>%
  mutate(Subtipo_Clean = case_when(
    is.na(Liquid.Subtype) | Liquid.Subtype == "" ~ "CRUDO / CO2 (Sin Subtipo)",
    grepl("DIESEL", Liquid.Subtype) ~ "DIESEL / JET FUEL / KEROSENE",
    grepl("GASOLINE", Liquid.Subtype) ~ "GASOLINA",
    grepl("LPG", Liquid.Subtype) ~ "LPG / NGL",
    grepl("OTHER HVL", Liquid.Subtype) ~ "OTROS HVL",
    TRUE ~ "OTROS (Mezclas, etc.)"
  )) %>%
  count(Subtipo_Clean, name = "ni") %>%
  mutate(hi_pct = round((ni / sum(ni)) * 100, 1))
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 = 4, fontface = "bold") +
  scale_fill_brewer(palette = "Blues", direction = -1) +
  
  labs(
    title = "Gráfica 6: Distribución de Accidentes por Subtipo de Líquido",
    fill = "Subtipo de Líquido"
  ) +
  
  theme_void() +
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold", margin = margin(b = 10)),
    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`

variable_limpia <- trimws(toupper(na.omit(datos$Liquid.Subtype)))
variable_limpia <- variable_limpia[variable_limpia != ""]
tabla_frecuencia <- table(variable_limpia)
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)
cat("--- Moda de Liquid.Subtype ---\n")
## --- Moda de 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("Cantidad de ocurrencias:", cantidad, "\n")
## Cantidad de ocurrencias: 408
cat("Porcentaje del total:", porcentaje, "%\n")
## Porcentaje del total: 30.24 %
#El análisis de la variable Liquid.Subtype 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.