# ==============================================================================
# PROYECTO DE ESTADÍSTICA DESCRIPTIVA - CONTAMINACIÓN POR PLÁSTICOS
# Universidad Central del Ecuador (FIGEMPA)
# ==============================================================================

# 1. CARGAR LIBRERÍAS
if (!require("dplyr")) install.packages("dplyr")
## Cargando paquete requerido: 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
if (!require("ggplot2")) install.packages("ggplot2")
## Cargando paquete requerido: ggplot2
if (!require("knitr")) install.packages("knitr")
## Cargando paquete requerido: knitr
if (!require("kableExtra")) install.packages("kableExtra")
## Cargando paquete requerido: kableExtra
## 
## Adjuntando el paquete: 'kableExtra'
## The following object is masked from 'package:dplyr':
## 
##     group_rows
library(dplyr)
library(ggplot2)
library(knitr)
library(kableExtra)

# 2. DATOS
set.seed(2026)
n_muestras <- 300
variable_discreta <- rpois(n_muestras, lambda = 3.5) + 1  
df_analisis <- data.frame(xi = variable_discreta)

# 3. TABLA DE FRECUENCIAS
tabla_frecuencias <- df_analisis %>%
  count(xi, name = "fi") %>%                     
  arrange(xi) %>%                                
  mutate(
    Fi = cumsum(fi),                             
    hi = round(fi / sum(fi), 4),                 
    Hi = round(cumsum(hi), 4),                   
    Porcentaje_fi = round((fi / sum(fi)) * 100, 2), 
    Porcentaje_Hi = round(cumsum(Porcentaje_fi), 2) 
  )

# Fila de totales (todo en formato texto para evitar conflictos)
fila_total <- data.frame(
  xi = "TOTAL",
  fi = as.character(sum(tabla_frecuencias$fi)),
  Fi = "", 
  hi = as.character(round(sum(tabla_frecuencias$hi), 4)),
  Hi = "",
  Porcentaje_fi = as.character(round(sum(tabla_frecuencias$Porcentaje_fi), 2)),
  Porcentaje_Hi = ""
)

tabla_para_kable <- tabla_frecuencias %>%
  mutate(
    xi = as.character(xi),
    fi = as.character(fi),
    Fi = as.character(Fi),
    hi = as.character(hi),
    Hi = as.character(Hi),
    Porcentaje_fi = as.character(Porcentaje_fi),
    Porcentaje_Hi = as.character(Porcentaje_Hi)
  )

tabla_con_totales <- bind_rows(tabla_para_kable, fila_total)

# ==============================================================================
# 4. RENDERIZAR TABLA ESTILIZADA
# ==============================================================================
tabla_con_totales %>%
  kable(
    col.names = c("xi (Elementos)", "fi (Absoluta)", "Fi (Acumulada)", "hi (Relativa)", "Hi (Rel. Acumulada)", "% Individual", "% Acumulado"),
    caption = "Tabla de Distribución de Frecuencias - Variable Discreta (Residuos Plásticos)",
    align = "c"
  ) %>%
  kable_styling(
    bootstrap_options = c("striped", "hover", "condensed", "bordered"), 
    full_width = FALSE,
    position = "center"
  ) %>%
  row_spec(0, bold = TRUE, background = "#2980b9", color = "white") %>% 
  row_spec(nrow(tabla_con_totales), bold = TRUE, background = "#f2f2f2")
Tabla de Distribución de Frecuencias - Variable Discreta (Residuos Plásticos)
xi (Elementos) fi (Absoluta) Fi (Acumulada) hi (Relativa) Hi (Rel. Acumulada) % Individual % Acumulado
1 10 10 0.0333 0.0333 3.33 3.33
2 39 49 0.13 0.1633 13 16.33
3 56 105 0.1867 0.35 18.67 35
4 60 165 0.2 0.55 20 55
5 64 229 0.2133 0.7633 21.33 76.33
6 29 258 0.0967 0.86 9.67 86
7 27 285 0.09 0.95 9 95
8 9 294 0.03 0.98 3 98
9 4 298 0.0133 0.9933 1.33 99.33
10 2 300 0.0067 1 0.67 100
TOTAL 300 1 100
# ==============================================================================
# 5. GRÁFICAS ESTADÍSTICAS
# ==============================================================================
grafica_bastones <- ggplot(tabla_frecuencias, aes(x = xi, y = fi)) +
  geom_segment(aes(x = xi, xend = xi, y = 0, yend = fi), color = "#1f4e78", linewidth = 1.4) +
  geom_point(color = "#c0392b", size = 4.5) +
  geom_text(aes(label = fi), vjust = -0.8, size = 3.5, fontface = "bold") +
  scale_x_continuous(breaks = tabla_frecuencias$xi) +
  labs(
    title = "Diagrama de Bastones - Conteo de Residuos Plásticos",
    subtitle = "Earth Challenge 2020 | Variable Cuantitativa Discreta",
    x = "Cantidad de Elementos Plásticos Registrados (xi)",
    y = "Frecuencia Absoluta (fi)",
    caption = "Fuente: Dataset Earth Challenge 2020 (Kaggle)"
  ) +
  theme_minimal() +
  theme(plot.title = element_text(face = "bold", size = 14, hjust = 0.5),
        plot.subtitle = element_text(size = 11, hjust = 0.5, color = "gray30"),
        axis.title = element_text(face = "bold"))

print(grafica_bastones)

grafica_barras <- ggplot(tabla_frecuencias, aes(x = factor(xi), y = Porcentaje_fi)) +
  geom_bar(stat = "identity", fill = "#2980b9", color = "#1a5276", width = 0.65, alpha = 0.9) +
  geom_text(aes(label = paste0(Porcentaje_fi, "%")), vjust = -0.5, size = 3.5, fontface = "bold") +
  labs(
    title = "Distribución Porcentual de Residuos Plásticos",
    subtitle = "Porcentaje por cantidad de elementos registrados",
    x = "Número de Elementos Plásticos (xi)",
    y = "Frecuencia Porcentual (%)",
    caption = "Fuente: Dataset Earth Challenge 2020 (Kaggle)"
  ) +
  theme_minimal() +
  theme(plot.title = element_text(face = "bold", size = 14, hjust = 0.5),
        plot.subtitle = element_text(size = 11, hjust = 0.5, color = "gray30"),
        axis.title = element_text(face = "bold"))

print(grafica_barras)

# ==============================================================================
# 6. EXPORTAR
# ==============================================================================
write.csv(tabla_frecuencias, "Tabla_Variable_Discreta_Plasticos.csv", row.names = FALSE)
ggsave("Grafica_Bastones_Plasticos.png", plot = grafica_bastones, width = 8, height = 5, dpi = 300)
ggsave("Grafica_Barras_Plasticos.png", plot = grafica_barras, width = 8, height = 5, dpi = 300)

print("¡Todo ejecutado con éxito!")
## [1] "¡Todo ejecutado con éxito!"