0.- Carga de Librerías

library(knitr)
library(dplyr)
library(readxl)
library(gt)

1.- Carga de Datos

carpeta_co <- file.path(Sys.getenv("USERPROFILE"), "Downloads", "Análisis Estadístico(CO AQI) - Cuantitativa Discreta")

ruta_xls     <- file.path(carpeta_co, "pollution_2000_2023.xls")
ruta_ni_xlsx <- file.path(carpeta_co, "ni_por_valor_CO.xlsx")

if (file.exists(ruta_xls)) {
  datos <- read_excel(ruta_xls)
} else if (file.exists(ruta_ni_xlsx)) {
  datos <- read_excel(ruta_ni_xlsx)
} else {
  stop("No se encontró el archivo de datos en la carpeta de CO AQI.")
}

dim(datos)
## [1] 102   5

2.- Selección de Variable

if ("CO AQI" %in% names(datos)) {
  variable_co <- suppressWarnings(as.numeric(datos$`CO AQI`))
  variable_co <- variable_co[!is.na(variable_co) & is.finite(variable_co)]
} else if (ncol(datos) >= 2 && names(datos)[2] %in% c("ni", "NI", "frecuencia", "Frecuencia")) {
  vals_u <- as.numeric(datos[[1]])
  ni_u   <- as.numeric(datos[[2]])
  ok     <- !is.na(vals_u) & !is.na(ni_u) & is.finite(vals_u) & is.finite(ni_u)
  variable_co <- rep(vals_u[ok], times = ni_u[ok])
} else {
  col_co <- names(datos)[grepl("^CO[._ ]?AQI$", names(datos), ignore.case = TRUE)][1]
  if (is.na(col_co)) stop("No se encontró la columna de CO AQI.")
  variable_co <- suppressWarnings(as.numeric(datos[[col_co]]))
  variable_co <- variable_co[!is.na(variable_co) & is.finite(variable_co)]
}

# Verificamos la cantidad de registros válidos para esta variable
length(variable_co)
## [1] 665414

3.- Conteo de frecuencias (Regla de Sturges)

# 1. Obtenemos el número total de datos válidos (n)
n <- length(variable_co)

# 2. Aplicamos la Regla de Sturges para calcular el número de intervalos (k)
k <- round(1 + 3.3 * log10(n))

# 3. Determinamos el valor mínimo y máximo de la variable
min_val <- min(variable_co, na.rm = TRUE)
max_val <- max(variable_co, na.rm = TRUE)

# 4. Calculamos la amplitud exacta (A) de cada intervalo
amplitud <- (max_val - min_val) / k

# 5. Generamos los límites inferiores (Li) y superiores (Ls) reales
Li <- seq(min_val, max_val - amplitud, length.out = k)
Ls <- seq(min_val + amplitud, max_val, length.out = k)

# 6. Calculamos la Marca de Clase exacta (MC / xi) a 4 decimales
MC <- round((Li + Ls) / 2, 4)
ni <- numeric(length(Li))

for (i in 1:length(Li)) {
  if (i < length(Li)) {
    ni[i] <- sum(variable_co >= Li[i] & variable_co < Ls[i])
  } else {
    ni[i] <- sum(variable_co >= Li[i] & variable_co <= Ls[i])
  }
}

N <- sum(ni)
hi <- (ni / N) * 100

Ni_asc <- cumsum(ni)
Ni_desc <- rev(cumsum(rev(ni)))

Hi_asc <- cumsum(hi)
Hi_desc <- rev(cumsum(rev(hi)))

# Vector de intervalos para las etiquetas de los gráficos (4 decimales)
Intervalo <- paste0("[", sprintf("%.4f", Li), " - ", sprintf("%.4f", Ls), ")")

4.- Tabla de distribución de frecuencias

# 1. Construcción del Data Frame base con formato a 4 decimales
TDF_CO <- data.frame(
  "Li_1" = sprintf("%.4f", Li),
  "Li" = sprintf("%.4f", Ls),
  "MC" = sprintf("%.4f", round(MC, 4)),
  "ni" = ni,
  "hi" = sprintf("%.4f", round(hi, 4)),
  "Ni_asc" = Ni_asc,
  "Ni_desc" = Ni_desc,
  "Hi_asc" = sprintf("%.4f", round(Hi_asc, 4)),
  "Hi_desc" = sprintf("%.4f", round(Hi_desc, 4)),
  stringsAsFactors = FALSE
)

# 2. Fila de totales
totales <- data.frame(
  "Li_1" = "Totales",
  "Li" = "",
  "MC" = "-",
  "ni" = sum(ni),
  "hi" = sprintf("%.4f", round(sum(hi), 4)),
  "Ni_asc" = "-",
  "Ni_desc" = "-",
  "Hi_asc" = "-",
  "Hi_desc" = "-",
  stringsAsFactors = FALSE
)

tabla_final <- rbind(TDF_CO, totales)

# 3. Maquetación avanzada con gt adaptada al formato formal de intervalos
tabla_final %>%
  gt() %>%
  tab_header(
    title = md("**Tabla Nro. 1**"),
    subtitle = md("Distribución de frecuencias del Índice de Calidad del Aire ($CO$ AQI) en EE.UU. (2000-2023)")
  ) %>%
  tab_spanner(
    label = "Variable X",
    columns = c(Li_1, Li)
  ) %>%
  cols_label(
    Li_1 = "xi-1",
    Li = "xi+1",
    MC = html("<i>x<sub>i</sub></i><br>MC"),
    ni = html("<i>n<sub>i</sub></i><br>(FA)"),
    hi = html("<i>h<sub>i</sub></i><br>(FR)"),
    Ni_asc = html("<i>N<sub>i</sub></i> ↓<br>(FAAA)"),
    Hi_asc = html("<i>F<sub>i</sub></i> ↓<br>(FRAa)"),
    Ni_desc = html("<i>N<sub>i</sub></i> ↑<br>(FAAd)"),
    Hi_desc = html("<i>F<sub>i</sub></i> ↑<br>(FRAd)")
  ) %>%
  tab_source_note(
    source_note = md("**Autor:** Alex Fernández - Ingeniería Ambiental (Grupo 6)<br>**Fuente:** [https://www.kaggle.com/datasets/guslovesmath/us-pollution-data-200-to-2022](https://www.kaggle.com/datasets/guslovesmath/us-pollution-data-200-to-2022)")
  ) %>%
  tab_options(
    table.border.top.color = "black",
    table.border.bottom.color = "black",
    table.border.top.width = px(3),
    table.border.bottom.width = px(3),
    heading.align = "center",
    heading.title.font.size = px(22),
    heading.subtitle.font.size = px(14),
    heading.background.color = "#F0F0F0",
    column_labels.font.weight = "bold",
    column_labels.font.size = px(14),
    column_labels.background.color = "#D3D3D3",
    column_labels.border.top.color = "black",
    column_labels.border.bottom.color = "black",
    column_labels.border.bottom.width = px(2),
    table_body.hlines.color = "#E0E0E0",
    table_body.vlines.color = "#E0E0E0",
    row.striping.include_table_body = TRUE,
    row.striping.background_color = "#F9F9F9",
    table.font.size = px(13),
    source_notes.font.size = px(11),
    source_notes.background.color = "#F0F0F0",
    data_row.padding = px(8)
  ) %>%
  tab_style(
    style = cell_borders(
      sides = c("left", "right"),
      color = "#E0E0E0",
      weight = px(1)
    ),
    locations = cells_body()
  ) %>%
  tab_style(
    style = cell_borders(
      sides = c("left", "right"),
      color = "black",
      weight = px(1.5)
    ),
    locations = cells_column_labels()
  ) %>%
  cols_align(
    align = "center",
    columns = everything()
  )
Tabla Nro. 1
Distribución de frecuencias del Índice de Calidad del Aire ( COCO AQI) en EE.UU. (2000-2023)
Variable X
xi
MC
ni
(FA)
hi
(FR)
Ni ↓
(FAAA)
Ni ↑
(FAAd)
Fi ↓
(FRAa)
Fi ↑
(FRAd)
xi-1 xi+1
0.0000 10.0500 5.0250 602523 90.5486 602523 665414 90.5486 100.0000
10.0500 20.1000 15.0750 51996 7.8141 654519 62891 98.3627 9.4514
20.1000 30.1500 25.1250 7620 1.1452 662139 10895 99.5078 1.6373
30.1500 40.2000 35.1750 2211 0.3323 664350 3275 99.8401 0.4922
40.2000 50.2500 45.2250 653 0.0981 665003 1064 99.9382 0.1599
50.2500 60.3000 55.2750 271 0.0407 665274 411 99.9790 0.0618
60.3000 70.3500 65.3250 76 0.0114 665350 140 99.9904 0.0210
70.3500 80.4000 75.3750 22 0.0033 665372 64 99.9937 0.0096
80.4000 90.4500 85.4250 15 0.0023 665387 42 99.9959 0.0063
90.4500 100.5000 95.4750 11 0.0017 665398 27 99.9976 0.0041
100.5000 110.5500 105.5250 4 0.0006 665402 16 99.9982 0.0024
110.5500 120.6000 115.5750 3 0.0005 665405 12 99.9986 0.0018
120.6000 130.6500 125.6250 2 0.0003 665407 9 99.9989 0.0014
130.6500 140.7000 135.6750 3 0.0005 665410 7 99.9994 0.0011
140.7000 150.7500 145.7250 0 0.0000 665410 4 99.9994 0.0006
150.7500 160.8000 155.7750 1 0.0002 665411 4 99.9995 0.0006
160.8000 170.8500 165.8250 0 0.0000 665411 3 99.9995 0.0005
170.8500 180.9000 175.8750 1 0.0002 665412 3 99.9997 0.0005
180.9000 190.9500 185.9250 1 0.0002 665413 2 99.9998 0.0003
190.9500 201.0000 195.9750 1 0.0002 665414 1 100.0000 0.0002
Totales - 665414 100.0000 - - - -
Autor: Alex Fernández - Ingeniería Ambiental (Grupo 6)
Fuente: https://www.kaggle.com/datasets/guslovesmath/us-pollution-data-200-to-2022

5.- Gráfica de distribución de frecuencias

5.1 Histograma de cantidad

if (!exists("Intervalo")) Intervalo <- paste0("[", sprintf("%.4f", Li), " - ", sprintf("%.4f", Ls), ")")
options(scipen = 999)
colores_profesionales <- c("#335C67", "#E09F3E", "#9E2A2B", "#540B0E", "#2B2D42", "#4A5759")

# Margen equilibrado (10) y distancia perfecta del título (7.5)
par(mar = c(10, 5, 4, 2) + 0.1)

misf_barras <- barplot(
  height = ni,
  names.arg = FALSE, 
  main = "Gráfica Nro. 1\nDistribución del Índice de Calidad del Aire (CO AQI)\nEstudio en EE.UU. (2000-2023)",
  xlab = "Intervalos de Clase (CO AQI)",
  ylab = "Cantidad",
  col = colores_profesionales,
  border = "black",
  space = 0,
  axes = FALSE,
  las = 1,
  cex.lab = 1,
  cex.main = 1,
  mgp = c(7.5, 1, 0)
)

axis(2, at = pretty(c(0, max(ni))), las = 1, cex.axis = 0.85)

axis(
  1, 
  at = misf_barras, 
  labels = Intervalo, 
  cex.axis = 0.55,  
  las = 2,          
  tick = FALSE
)

grid(nx = NA, ny = NULL, col = "lightgray", lty = 1)

5.2 Histograma con respecto al total

if (!exists("Intervalo")) Intervalo <- paste0("[", sprintf("%.4f", Li), " - ", sprintf("%.4f", Ls), ")")
options(scipen = 999)
colores_profesionales <- c("#335C67", "#E09F3E", "#9E2A2B", "#540B0E", "#2B2D42", "#4A5759")

par(mar = c(10, 5, 4, 2) + 0.1)
techo_muestra <- N

misf_barras_2 <- barplot(
  height = ni,
  names.arg = FALSE, 
  main = "Gráfica Nro. 2\nDistribución con respecto al total (CO AQI)\nEstudio en EE.UU. (2000-2023)",
  xlab = "Intervalos de Clase (CO AQI)",
  ylab = "Cantidad",
  col = colores_profesionales,
  border = "black",
  space = 0,
  ylim = c(0, techo_muestra),
  axes = FALSE,
  las = 1,
  cex.lab = 1,
  cex.main = 1,
  mgp = c(7.5, 1, 0)
)

marcas_y <- seq(0, techo_muestra, by = 100000)

axis(
  2,
  at = marcas_y,
  labels = marcas_y,
  las = 1,
  cex.axis = 0.85
)

axis(
  1, 
  at = misf_barras_2, 
  labels = Intervalo, 
  cex.axis = 0.55, 
  las = 2, 
  tick = FALSE
)

grid(
  nx = NA,
  ny = NULL,
  col = "lightgray",
  lty = 1
)

5.3 Histograma Porcentual

colores_profesionales <- c("#335C67", "#E09F3E", "#9E2A2B", "#540B0E", "#2B2D42", "#4A5759")

par(mar = c(10, 5, 4, 2) + 0.1)

misf_barras_3 <- barplot(
  height = hi,
  names.arg = FALSE, 
  main = "Gráfica Nro. 3\nDistribución porcentual del Índice de Calidad del Aire (CO AQI)\nEstudio en EE.UU. (2000-2023)",
  xlab = "Intervalos de Clase (CO AQI)",
  ylab = "Porcentaje",
  col = colores_profesionales,
  border = "black",
  space = 0,
  ylim = c(0, max(hi) * 1.15),
  axes = FALSE,
  las = 1,
  cex.lab = 1,
  cex.main = 1,
  mgp = c(7.5, 1, 0)
)

marcas_y_porc <- pretty(c(0, max(hi)))

axis(
  2,
  at = marcas_y_porc,
  labels = paste0(marcas_y_porc, "%"),
  las = 1,
  cex.axis = 0.85
)

axis(
  1, 
  at = misf_barras_3, 
  labels = Intervalo, 
  cex.axis = 0.55, 
  las = 2, 
  tick = FALSE
)

grid(
  nx = NA,
  ny = NULL,
  col = "lightgray",
  lty = 1
)

5.4 Histograma porcentual con respecto al todo

colores_profesionales <- c("#335C67", "#E09F3E", "#9E2A2B", "#540B0E", "#2B2D42", "#4A5759")

par(mar = c(10, 5, 4, 2) + 0.1)

misf_barras_4 <- barplot(
  height = hi,
  names.arg = FALSE, 
  main = "Gráfica Nro. 4\nDistribución porcentual con respecto al todo (CO AQI)\nEstudio en EE.UU. (2000-2023)",
  xlab = "Intervalos de Clase (CO AQI)",
  ylab = "Porcentaje",
  col = colores_profesionales,
  border = "black",
  space = 0,
  ylim = c(0, 100),
  axes = FALSE,
  las = 1,
  cex.lab = 1,
  cex.main = 1,
  mgp = c(7.5, 1, 0)
)

marcas_y_100 <- seq(0, 100, by = 20)

axis(
  2,
  at = marcas_y_100,
  labels = paste0(marcas_y_100, "%"),
  las = 1,
  cex.axis = 0.85
)

axis(
  1, 
  at = misf_barras_4, 
  labels = Intervalo, 
  cex.axis = 0.55, 
  las = 2, 
  tick = FALSE
)

grid(
  nx = NA,
  ny = NULL,
  col = "lightgray",
  lty = 1
)

5.5 Diagrama de Caja y Bigotes

options(scipen = 999)
par(mar = c(5, 5, 4, 2) + 0.1)

cortes_sturges <- c(Li, max(Ls))

h_fondo <- hist(
  variable_co,
  breaks = cortes_sturges,
  freq = TRUE,
  main = "Gráfica Nro. 5\nDistribución del Índice de Calidad del Aire (CO AQI)\nen EE.UU. (2000-2023)",
  xlab = "Índice de Calidad del Aire (CO AQI)",
  ylab = "Cantidad",
  col = adjustcolor("#335C67", alpha.f = 0.25),
  border = "#335C67",
  las = 1,
  cex.main = 1,
  cex.lab = 1,
  mgp = c(3.8, 1, 0),
  axes = FALSE
)

axis(1, at = pretty(c(min_val, max_val)), cex.axis = 0.85)
axis(2, at = pretty(c(0, max(h_fondo$counts))), las = 1, cex.axis = 0.85)

grid(
  nx = NULL,
  ny = NULL,
  col = "lightgray",
  lty = 1
)

altura_caja <- max(h_fondo$counts) * 0.45
grosor_caja <- max(h_fondo$counts) * 0.18

boxplot(
  variable_co,
  horizontal = TRUE,
  add = TRUE,
  at = altura_caja,
  boxwex = grosor_caja,
  col = adjustcolor("#E09F3E", alpha.f = 0.85),
  border = "black",
  pch = 1,
  cex = 0.7,
  axes = FALSE
)

5.6 Diagrama de Ojivas

5.6.1 Diagrama de Ojivas (Ni)

# Margen equilibrado (10) y distancia perfecta del título (7.5)
par(mar = c(10, 5, 4, 2) + 0.1)

# Usamos los límites superiores de los intervalos
x <- Ls

# Ojiva Ascendente (Menor que) con tonos sobrios y profesionales
plot(
  x, Ni_asc,
  type = "b",
  col = "#335C67",
  pch = 19,
  lwd = 2,
  main = "Gráfica Nro. 6\nDistribución Acumulada (Ojivas) del CO AQI\nEstudio en EE.UU. (2000-2023)",
  xlab = "Límites Superiores (CO AQI)",
  ylab = "Cantidad",
  ylim = c(0, N),
  axes = FALSE,
  las = 1,
  cex.lab = 1,
  cex.main = 1,
  mgp = c(7.5, 1, 0)
)

# Ojiva Descendente (Mayor que)
lines(
  x, Ni_desc,
  type = "b",
  col = "#540B0E",
  pch = 19,
  lwd = 2
)

# Eje X con límites en vertical (las = 2) y tamaño optimizado (0.55)
axis(
  1,
  at = x,
  labels = round(x, 2),
  las = 2,
  cex.axis = 0.55,
  tick = FALSE
)

# Eje Y con marcas dinámicas bonitas
marcas_y_ojiva <- pretty(c(0, N))

axis(
  2,
  at = marcas_y_ojiva,
  labels = marcas_y_ojiva,
  las = 1,
  cex.axis = 0.85
)

grid(
  nx = NA,
  ny = NULL,
  col = "lightgray",
  lty = 1
)

# Leyenda profesional y sobria
legend(
  "topright",
  legend = c("Ascendente (Ojiva Menor que)", "Descendente (Ojiva Mayor que)"),
  col = c("#335C67", "#540B0E"),
  lty = 1,
  pch = 19,
  bty = "n",
  cex = 0.85
)

5.6.2 Diagrama de Ojivas Porcentuales (Hi)

# Margen equilibrado (10) y distancia perfecta del título (7.5)
par(mar = c(10, 5, 4, 2) + 0.1)

# Usamos los límites superiores de los intervalos
x <- Ls

# Ojiva Ascendente Porcentual con tonos sobrios y profesionales
plot(
  x, Hi_asc,
  type = "b",
  col = "#335C67",
  pch = 19,
  lwd = 2,
  main = "Gráfica Nro. 7\nOjiva Porcentual del Índice de Calidad del Aire (CO AQI)\nEstudio en EE.UU. (2000-2023)",
  xlab = "Límites Superiores (CO AQI)",
  ylab = "Porcentaje (%)",
  ylim = c(0, 100),
  axes = FALSE,
  las = 1,
  cex.lab = 1,
  cex.main = 1,
  mgp = c(7.5, 1, 0)
)

# Ojiva Descendente Porcentual
lines(
  x, Hi_desc,
  type = "b",
  col = "#540B0E",
  pch = 19,
  lwd = 2
)

# Eje X con límites en vertical (las = 2) y tamaño optimizado (0.55)
axis(
  1,
  at = x,
  labels = round(x, 2),
  las = 2,
  cex.axis = 0.55,
  tick = FALSE
)

# Eje Y con formato porcentual limpio (0%, 20%, 40%, etc.)
marcas_y_porc <- seq(0, 100, by = 20)

axis(
  2,
  at = marcas_y_porc,
  labels = paste0(marcas_y_porc, "%"),
  las = 1,
  cex.axis = 0.85
)

grid(
  nx = NA,
  ny = NULL,
  col = "lightgray",
  lty = 1
)

# Leyenda profesional y sobria
legend(
  "topright",
  legend = c("Ascendente (Menor que)", "Descendente (Mayor que)"),
  col = c("#335C67", "#540B0E"),
  lty = 1,
  pch = 19,
  bty = "n",
  cex = 0.85
)

6.- Indicadores

x_var <- variable_co

moda_calc <- function(v) {
  uniqv <- unique(v)
  uniqv[which.max(tabulate(match(v, uniqv)))]
}

# INDICADORES DE TENDENCIA CENTRAL
X  <- mean(x_var, na.rm = TRUE)
Me <- median(x_var, na.rm = TRUE)
Mo <- moda_calc(x_var)

# INDICADORES DE DISPERSIÓN
Rango_val <- paste0("[", min(x_var, na.rm = TRUE), " - ", max(x_var, na.rm = TRUE), "]")
var_co    <- var(x_var, na.rm = TRUE)
desv      <- sd(x_var, na.rm = TRUE)
CV        <- (desv / X) * 100

# INDICADORES DE FORMA (Nativos en R)
n_obs <- length(x_var)
As <- sum((x_var - X)^3, na.rm = TRUE) / (n_obs * (desv^3))
K  <- (sum((x_var - X)^4, na.rm = TRUE) / (n_obs * (desv^4))) - 3

# Conteo de valores atípicos (método estándar de cuartiles / IQR)
Q1 <- quantile(x_var, 0.25, na.rm = TRUE)
Q3 <- quantile(x_var, 0.75, na.rm = TRUE)
IQR_val <- Q3 - Q1
lim_superior_atipico <- Q3 + 1.5 * IQR_val
num_atipicos <- sum(x_var > lim_superior_atipico, na.rm = TRUE)
texto_atipicos <- paste0(num_atipicos, " atípicos (> ", round(lim_superior_atipico, 1), ")")

df_resumen <- data.frame(
  Variable = "CO AQI",
  Rango = Rango_val,
  X = round(X, 2),
  Me = round(Me, 2),
  Mo = as.character(Mo),
  sd = round(desv, 2),
  CV = round(CV, 2),
  As = round(As, 2),
  K = round(K, 2),
  Atípicos = texto_atipicos
)

df_resumen %>%
  gt() %>%
  tab_header(
    title = md("**Tabla Nro. 2**"),
    subtitle = "Indicadores Estadísticos del Índice de Calidad del Aire (CO AQI), estudio en EE.UU. (2000-2023)"
  ) %>%
  cols_label(
    Variable = "Variable",
    Rango = "Rango",
    X = "X̄",
    Me = "Me",
    Mo = "Mo",
    sd = "sd",
    CV = "CV (%)",
    As = "As",
    K = "K",
    Atípicos = "Valores atípicos"
  ) %>%
  opt_table_outline() %>%
  tab_options(
    table.font.size = px(13),
    heading.title.font.size = px(16),
    heading.subtitle.font.size = px(12),
    column_labels.background.color = "#EAEAEA",
    table.border.top.color = "black",
    table.border.bottom.color = "black"
  )
Tabla Nro. 2
Indicadores Estadísticos del Índice de Calidad del Aire (CO AQI), estudio en EE.UU. (2000-2023)
Variable Rango X̄ Me Mo sd CV (%) As K Valores atípicos
CO AQI [0 - 201] 5.25 3 2 5.01 95.48 3.62 33.73 32640 atípicos (> 14.5)

7.- Conclusión

El índice CO AQI en EE.UU. (2000–2023) presenta un rango de [0 - 201] y se concentra en [0.0000 - 10.0500) con 602,523 registros (90.55%), con media de 5.25, mediana de 3 y moda de 2.

Presenta desviación estándar de 5.01 (CV 95.48%), asimetría de 3.62, curtosis de 33.73 y 32,640 valores atípicos superiores a 14.5.