library(dplyr)
## 
## Adjuntando el paquete: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(knitr)
library(kableExtra)
## 
## Adjuntando el paquete: 'kableExtra'
## The following object is masked from 'package:dplyr':
## 
##     group_rows
TDF_causa <- datos %>%
  count(Cause.Category, name = "ni") %>%       
  arrange(desc(ni)) %>%                        
  mutate(hi = (ni / sum(ni)) * 100) %>%        
  mutate(hi = sprintf("%.2f", round(hi, 2)))   
Sumatoria <- data.frame(
  Cause.Category = "TOTAL",
  ni = sum(TDF_causa$ni),
  hi = "100.00"
)

TDF_final <- rbind(TDF_causa, Sumatoria)
colnames(TDF_final) <- c("Causa del Accidente", "ni", "hi (%)")
kable(TDF_final, align = 'c', 
      caption = "Tabla de Frecuencia: Causas de Accidentes") %>%
  kable_styling(full_width = FALSE, position = "center", 
                bootstrap_options = c("striped", "hover", "bordered")) %>%
  row_spec(nrow(TDF_final), bold = TRUE, background = "#f2f2f2") %>%
  row_spec(1, bold = TRUE, color = "black")
Tabla de Frecuencia: Causas de Accidentes
Causa del Accidente ni hi (%)
MATERIAL/WELD/EQUIP FAILURE 1435 51.34
CORROSION 592 21.18
INCORRECT OPERATION 378 13.52
ALL OTHER CAUSES 118 4.22
NATURAL FORCE DAMAGE 118 4.22
EXCAVATION DAMAGE 97 3.47
OTHER OUTSIDE FORCE DAMAGE 57 2.04
TOTAL 2795 100.00
#barra general ni
library(ggplot2)
library(dplyr)
datos_causa <- datos %>%
  count(Cause.Category, name = "ni")
ggplot(datos_causa, aes(x = reorder(Cause.Category, -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 1: Cantidad de Accidentes por Causa generales",
    x = "Causa del Accidente",
    y = "Número de Accidentes"
  ) +
  
  theme_classic() +
  theme(
    axis.text.x = element_text(angle = 45, hjust = 1, size = 8),
    plot.title = element_text(face = "bold")
  )

#barra local ni
library(ggplot2)
library(dplyr)
datos_causa <- datos %>%
  count(Cause.Category, name = "ni")
ggplot(datos_causa, aes(x = reorder(Cause.Category, -ni), y = ni)) +
  
  geom_bar(stat = "identity", fill = "skyblue", width = 0.7) +
  scale_y_continuous(limits = c(0, 1500), breaks = seq(0, 2000, by = 500)) +
  labs(
    title = "Gráfica 2: Cantidad de Accidentes por Causa",
    x = "Causa del Accidente",
    y = "Número de Accidentes"
  ) +
  
  theme_classic() +
  theme(
    axis.text.x = element_text(angle = 45, hjust = 1, size = 8),
    plot.title = element_text(face = "bold")
  )

#barra local hi
library(ggplot2)
library(dplyr)

datos_causa_local <- datos %>%
  count(Cause.Category, name = "ni") %>%
  mutate(hi_pct = (ni / sum(ni)) * 100) 

ggplot(datos_causa_local, aes(x = reorder(Cause.Category, -hi_pct), y = hi_pct)) +
  
  geom_bar(stat = "identity", fill = "skyblue", width = 0.7) +
  
  scale_y_continuous(limits = c(0, 60), breaks = seq(0, 60, by = 10)) +
  
  labs(
    title = "Gráfica 3: Cantidad de categoría por Causa",
    x = "Causa del Accidente",
    y = "Porcentaje (%)"
  ) +
  
  theme_classic() +
  theme(
    axis.text.x = element_text(angle = 45, hjust = 1, size = 8),
    plot.title = element_text(face = "bold")
  )

#barra global hi
library(ggplot2)
library(dplyr)
datos_causa_local <- datos %>%
  count(Cause.Category, name = "ni") %>%
  mutate(hi_pct = (ni / sum(ni)) * 100) 
ggplot(datos_causa_local, aes(x = reorder(Cause.Category, -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 4: Cantidad de categoría por pocentaje",
    x = "Causa del Accidente",
    y = "Porcentaje (%)"
  ) +
  
  theme_classic() +
  
  theme(
    axis.text.x = element_text(angle = 45, hjust = 1, size = 8),
    plot.title = element_text(face = "bold")
  )

#diagrama circular
library(ggplot2)
library(dplyr)
datos_pastel <- datos %>%
  count(Cause.Category, name = "ni") %>%
  mutate(hi_pct = round((ni / sum(ni)) * 100, 2)) %>%
  arrange(desc(ni))
ggplot(datos_pastel, aes(x = "", y = hi_pct, fill = Cause.Category)) +
  
  geom_bar(stat = "identity", width = 1, color = "white", size = 1.2) +
  coord_polar("y", start = 0) +
  geom_text(aes(label = paste0(hi_pct, "%")), 
            position = position_stack(vjust = 0.5), 
            color = "black", fontface = "bold", size = 3.5) +
  scale_fill_brewer(palette = "Blues", direction = -1) +
  labs(
    title = "Gráfica 5: Distribución de Causas",
    fill = "Causa del Accidente"
  ) +
  
  theme_void() + 
  
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold", size = 14),
    legend.position = "right" 
  )
## Warning in geom_bar(stat = "identity", width = 1, color = "white", size = 1.2):
## Ignoring unknown parameters: `size`

#moda
tabla_causas <- table(na.omit(datos$Cause.Category))
causa_top <- names(tabla_causas)[which.max(tabla_causas)]
cantidad_top <- max(tabla_causas)
total_eventos <- sum(tabla_causas)
porcentaje_top <- round((cantidad_top / total_eventos) * 100, 2)

# 4. Imprimir resultados
cat("La causa principal de los accidentes es:", causa_top, "\n")
## La causa principal de los accidentes es: MATERIAL/WELD/EQUIP FAILURE
cat("Ocurrió", cantidad_top, "veces, lo que representa el", porcentaje_top, "% del total de casos.\n")
## Ocurrió 1435 veces, lo que representa el 51.34 % del total de casos.
#Conclusión
#Al examinar las categorías de causa, se destaca que los factores vinculados a fallas del equipo son los más recurrentes (Moda:MATERIAL/WELD/EQUIP FAILURE ). Sin embargo, las causas externas o humanas, como operaciones incorrectas, mantienen una presencia significativa. Los gráficos muestra que, aunque la infraestructura es el punto crítico principal, los procedimientos operativos también contribuyen notablemente a la siniestralidad global.