0. Librerías

library(readr)
library(knitr)
library(kableExtra)
library(dplyr)
library(ggplot2)

1. Leer Datos

variables <- read.csv("C:/Users/dellh/Downloads/GlobalWeatherRepository.csv")

2. Depuración y Selección de Variables

EPA <- na.omit(variables$air_quality_us.epa.index)

3. Tabla de distribución de frecuencia

Tabla_EPA <- table(EPA)

ni_EPA <- as.vector(Tabla_EPA) 
hi_EPA <- round((ni_EPA / sum(ni_EPA)) * 100, 2)

TDF_EPA_Base <- data.frame(
  EPA = names(Tabla_EPA),
  ni = ni_EPA,
  hi = hi_EPA
)
sumatoria_EPA <- data.frame(
  EPA = "TOTAL", 
  ni = sum(ni_EPA), 
  hi = 100
)
TDF_EPA_Suma <- rbind(TDF_EPA_Base, sumatoria_EPA)

colnames(TDF_EPA_Suma) <- c("EPA", "Frecuencia Absoluta (ni)", "Frecuencia Relativa (hi %)")

kable(TDF_EPA_Suma, 
      align = "c",
      caption =  "Tabla N°1:Distribución de frecuencia del índice 
      de calidad del aire según escala 
      (AQI EPA) del año 2024 hasta 2026 ") |> 
  kable_styling(full_width = TRUE, position = "center",
                bootstrap_options = c("striped", "hover", "condensed", "responsive")) |> 
  row_spec(0, bold = TRUE, color = "white", background = "#90D5FF") |> 
  row_spec(nrow(TDF_EPA_Suma), bold = TRUE, background = "#d3d3d3") |> 
  footnote(general =     "Fuente: Global Weather Repository,(https://www.kaggle.com/datasets/nelgiriyewithana/global-weather-repository)",
           general_title = "Nota: Grupo N°2",
           footnote_as_chunk = TRUE,
           title_format = c("italic", "bold"))
Tabla N°1:Distribución de frecuencia del índice de calidad del aire según escala (AQI EPA) del año 2024 hasta 2026
EPA Frecuencia Absoluta (ni) Frecuencia Relativa (hi %)
1 76644 54.09
2 44207 31.20
3 11301 7.98
4 7916 5.59
5 1189 0.84
6 446 0.31
TOTAL 141703 100.00
Nota: Grupo N°2 Fuente: Global Weather Repository,(https://www.kaggle.com/datasets/nelgiriyewithana/global-weather-repository)

4. Tabla de frecuencia simplificada

EPA <- as.numeric(EPA)
EPA_Categoria <- cut(
  EPA,
  breaks = c(0, 2, 4, 6),
  labels = c("Bajo", "Medio", "Alto"),
  include.lowest = TRUE
)
Tabla_EPA <- table(EPA_Categoria)

ni_EPA <- as.vector(Tabla_EPA)

hi_EPA <- round((ni_EPA / sum(ni_EPA)) * 100, 2)

TDF_EPA_Base <- data.frame(
  Categoria = names(Tabla_EPA),
  ni = ni_EPA,
  hi = hi_EPA
)

sumatoria_EPA <- data.frame(
  Categoria = "TOTAL",
  ni = sum(ni_EPA),
  hi = 100
)

TDF_EPA_Suma <- rbind(TDF_EPA_Base, sumatoria_EPA)

colnames(TDF_EPA_Suma) <- c(
  "Clasificación EPA",
  "Frecuencia Absoluta (ni)",
  "Frecuencia Relativa (hi %)"
)

kable(
  TDF_EPA_Suma,
  align = "c",
  caption = "Tabla N°2: Resumen de niveles de calidad del aire (Escala EPA) en período 2024-2026"
) %>%
  kable_styling(
    full_width = TRUE,
    position = "center",
    bootstrap_options = c("striped", "hover", "condensed", "responsive")
  ) %>%
  row_spec(0, bold = TRUE, color = "white", background = "#2cD") %>%
  row_spec(nrow(TDF_EPA_Suma), bold = TRUE, background = "#EAEDED") %>%
  footnote(
    general = "Fuente: Global Weather Repository (Kaggle).",
    general_title = "Nota:Elaborado Grupo N°2 ",
    footnote_as_chunk = TRUE,
    title_format = c("italic", "bold")
  )
Tabla N°2: Resumen de niveles de calidad del aire (Escala EPA) en período 2024-2026
Clasificación EPA Frecuencia Absoluta (ni) Frecuencia Relativa (hi %)
Bajo 120851 85.28
Medio 19217 13.56
Alto 1635 1.15
TOTAL 141703 100.00
Nota:Elaborado Grupo N°2 Fuente: Global Weather Repository (Kaggle).

5. Gráfica de distribución de frecuencia

5.1 Diagrama de barra (ni)AQI

# Frecuencias por categoría

Tabla_EPA <- table(EPA_Categoria)

datos_grafica <- data.frame(
  Categoria = names(Tabla_EPA),
  Frecuencia = as.vector(Tabla_EPA)
)

# Orden correcto de las categorías

datos_grafica$Categoria <- factor(
  datos_grafica$Categoria,
  levels = c("Bajo", "Medio", "Alto")
)

ggplot(datos_grafica,
       aes(x = Categoria,
           y = Frecuencia,
           fill = Categoria)) +
  
  geom_col(width = 0.6, color = "black") +
  
  geom_text(
    aes(label = Frecuencia),
    vjust = -0.5,
    fontface = "bold",
    size = 3
  ) +
  
  scale_fill_manual(
    values = c(
      "Bajo" = "lavender",
      "Medio" = "yellow",
      "Alto" = "pink"
      
    )
  ) +
  
  labs(
    title = "Clasificación del Índice AQI según escala EPA 
                     el año 2024 al 2026",
    x = "Categorías EPA",
    y = "Frecuencia Absoluta (ni)"
  ) +
  
  theme_minimal() +
  
  theme(
    plot.title = element_text(face = "bold", hjust = 0.5),
    axis.title = element_text(face = "bold"),
    legend.position = "none"
  )

5.2. Distribución de frecuencia (ni)con relación total

# Frecuencias por categoría
Tabla_EPA <- table(EPA_Categoria)

# Frecuencia absoluta
ni_EPA <- as.vector(Tabla_EPA)

# Tamaño muestral
N <- sum(ni_EPA)

# Datos para la gráfica
datos_grafica <- data.frame(
  Categoria = names(Tabla_EPA),
  ni = ni_EPA
)

# Orden correcto de categorías
datos_grafica$Categoria <- factor(
  datos_grafica$Categoria,
  levels = c("Bajo", "Medio", "Alto")
)

# Diagrama de barras global
ggplot(datos_grafica,
       aes(x = Categoria,
           y = ni,
           fill = Categoria)) +
  
  geom_col(width = 0.6, color = "blue") +
  
  geom_text(
    aes(label = ni),
    vjust = -0.5,
    fontface = "bold",
    size = 4
  ) +
  
  scale_fill_manual(
    values = c(
      "Bajo" = "lavender",
      "Medio" = "yellow",
      "Alto" = "pink"
    )
  ) +
  
  scale_y_continuous(
    limits = c(0, N),
    breaks = seq(0, N, by = 20000)
  ) +
  
  labs(
    title = "Frecuencia de niveles de calidad de aire según escala 
              EPA  desde 2024 hasta 2026",
    subtitle = paste("Tamaño muestral N =", N),
    x = "Categorías EPA",
    y = "Frecuencia Absoluta (ni)"
  ) +
  
  theme_minimal() +
  
  theme(
    plot.title = element_text(face = "bold", hjust = 0.5),
    plot.subtitle = element_text(face = "bold", hjust = 0.5),
    axis.title = element_text(face = "bold"),
    legend.position = "none"
  )

5.3 Distribución de frecuencia (hi) original

N <- sum(ni_EPA)

datos_grafica <- data.frame(
  Categoria = names(Tabla_EPA),
  ni = ni_EPA
)

# Frecuencia relativa porcentual
datos_grafica$hi <- round((datos_grafica$ni / N) * 100, 2)

# Orden correcto

datos_grafica$Categoria <- factor(
  datos_grafica$Categoria,
  levels = c("Bajo", "Medio", "Alto")
)

ggplot(datos_grafica,
       aes(x = Categoria,
           y = hi,
           fill = Categoria)) +
  
  geom_col(width = 0.6, color = "black") +
  
  geom_text(
    aes(label = paste0(hi, "%")),
    vjust = -0.5,
    fontface = "bold",
    size = 4
  ) +
  
  scale_fill_manual(
    values = c(
      "Bajo" = "lavender",
      "Medio" = "yellow",
      "Alto" = "pink"
     
    )
  ) +
  
  labs(
    title = "Distribución de frecuencia del Índice AQI según 
                  escala EPA desde el año 2024 hasta 2026",
    subtitle = paste("Tamaño de muestra (N) =", N),
    x = "Categorías EPA",
    y = "Frecuencia Relativa (%)"
  ) +
  
  ylim(0, max(datos_grafica$hi) + 5) +
  
  theme_minimal() +
  
  theme(
    plot.title = element_text(face = "bold", hjust = 0.5),
    plot.subtitle = element_text(face = "bold", hjust = 0.5),
    axis.title = element_text(face = "bold"),
    legend.position = "none"
  )

5.4 Distribución EPA (hi)

datos_hi <- data.frame(
  Categoria = names(Tabla_EPA),
  hi = hi_EPA
)

datos_hi$Categoria <- factor(
  datos_hi$Categoria,
  levels = c("Bajo", "Medio", "Alto")
)

ggplot(datos_hi,
       aes(x = Categoria,
           y = hi,
           fill = Categoria)) +
  
  geom_col(width = 0.6, color = "blue") +
  
  geom_text(
    aes(label = paste0(hi, "%")),
    vjust = -0.5,
    fontface = "bold",
    size = 4
  ) +
  
  scale_fill_manual(
    values = c(
      "Bajo" = "lavender",
      "Medio" = "yellow",
      "Alto" = "pink"
      
    )
  ) +
  
  scale_y_continuous(
    limits = c(0, 100),
    breaks = seq(0, 100, by = 10)
  ) +
  
  labs(
    title = "Distribución de frecuencia relativa
          (hi) del Índice AQI según  escala EPA desde
           2024 hasta 2026",
    subtitle = paste("Tamaño muestral N =", N),
    x = "Categorías EPA",
    y = "Frecuencia Relativa (%)"
  ) +
  
  theme_minimal() +
  
  theme(
    plot.title = element_text(face = "bold", hjust = 0.5),
    plot.subtitle = element_text(face = "bold", hjust = 0.5),
    axis.title = element_text(face = "bold"),
    legend.position = "none"
  )

##5.5. Diagrama Circular

# Estructura ampliar margen
par(mar = c(4,4,4,8))

Tabla_EPA <- table(EPA_Categoria)

porcentaje <- round(prop.table(Tabla_EPA) * 100, 2)

#Crea el gráfico
pie(
  Tabla_EPA,
  labels = paste0(porcentaje, "%"),
  col = c("lavender", "yellow", "pink"), 
  main = "Gráfica N°2: Distribución porcentual AQI EPA  
              desde el año 2024 hasta el 2026",
  border = "blue",
  radius = 0.9
)
# Agregar Leyenda

legend("topright",
       inset = c(-0.30,0),
       legend = c("Bajo", "Medio", "Alto"),
       fill = c("lavender", "yellow", "pink"),
       title = "Categorías",
       xpd =TRUE
)

6. Indicadores de frecuencia

Indicador de posición

# Mediana
EPA_ordinal <- factor(
  EPA_Categoria,
  levels = c("Bajo", "Medio", "Alto"),
  ordered = TRUE
)

Mediana <- levels(EPA_ordinal)[round(median(as.numeric(EPA_ordinal)))]

# Moda
Tabla_EPA_Categoria <- table(EPA_Categoria)

Moda <- names(Tabla_EPA_Categoria)[which.max(Tabla_EPA_Categoria)]

Rango

#Amplitud del rango
max(EPA) - min(EPA)
## [1] 5
Rango <- "Bajo - Alto"

Indicadores de posición

# Desviación estándar


# Varianza


# Coeficiente de variación (%)

Indicador de forma

# Asimetría


# Curtosis

Tabla de Indicadores

Indicadores_EPA <- data.frame(
  "Variable" = "EPA (Índice AQI)",
  "Rango " = "Bajo - Alto",
  "Medida" = Mediana,
  "Valor más frecuente (Moda)" = Moda
)

kable(
  Indicadores_EPA,
  align = "c",
  caption = "Tabla N°3. Indicadores estadísticos del índice de calidad del aire (AQI) según la escala EPA en el Global Weather Repository desde el 2024 hasta el 2026"
) |>
  kable_styling(
    full_width = FALSE,
    position = "center",
    bootstrap_options = c("striped", "hover")
  ) |>
  row_spec(
    0,
    bold = TRUE,
    color = "white",
    background = "#34495E"
  ) |>
  footnote(
    general = "Fuente: Global Weather Repository (Kaggle).",
    general_title = "Nota: Grupo N°2.",
    footnote_as_chunk = TRUE
  )
Tabla N°3. Indicadores estadísticos del índice de calidad del aire (AQI) según la escala EPA en el Global Weather Repository desde el 2024 hasta el 2026
Variable Rango. Medida Valor.más.frecuente..Moda.
EPA (Índice AQI) Bajo - Alto Bajo Bajo
Nota: Grupo N°2. Fuente: Global Weather Repository (Kaggle).

7. Conclusiones

La distribución de la variable EPA presenta una clara concentración en la categoría Bajo, tanto en términos de frecuencia como de posición central. Esto indica que la mayoría de las observaciones registradas entre 2024 y 2026 corresponden a condiciones de calidad del aire consideradas satisfactorias, con una baja presencia de categorías asociadas a mayores niveles de contaminación.