Autor: Yesid González | Fuente: Calidad del Aire en Colombia (Promedio Anual)
El modelo de regresión lineal simple se define como:
\[y = \beta_0 + \beta_1 x + \varepsilon\]
donde:
Se lee el archivo CSV desde el directorio del proyecto, se limpian separadores de miles y se filtran registros válidos de \(\text{PM}_{2.5}\) con exposición de 24 horas, representatividad temporal \(\ge 75\%\) en Bogotá, D.C.
archivo_csv <- "Calidad_del_Aire_en_Colombia_(Promedio_Anual)_20261124.csv"
raw_data <- read.csv(archivo_csv, stringsAsFactors = FALSE, check.names = FALSE)
limpiar_num <- function(x) {
as.numeric(gsub(",", "", trimws(as.character(x))))
}
datos_filtrados <- raw_data %>%
mutate(
anio_num = limpiar_num(`Año`),
promedio_num = limpiar_num(`Promedio`),
p98_num = limpiar_num(`Percentil 98`),
maximo_num = limpiar_num(`Máximo`),
rep_temp_num = limpiar_num(`Representatividad Temporal`),
expo_horas = limpiar_num(`Tiempo de exposición (horas)`),
depto_norm = toupper(iconv(`Nombre del Departamento`, from = "", to = "ASCII//TRANSLIT"))
) %>%
filter(
trimws(`Variable`) == "PM2.5",
expo_horas == 24,
!is.na(rep_temp_num), rep_temp_num >= 75,
grepl("BOGOT", depto_norm),
!is.na(promedio_num), !is.na(p98_num),
promedio_num > 0, p98_num > 0
) %>%
select(
Estacion = `Estación`,
Municipio = `Nombre del Municipio`,
Anio = anio_num,
Promedio = promedio_num,
Percentil98 = p98_num,
Maximo = maximo_num,
Representatividad = rep_temp_num
)
cat("Total de registros filtrados:", nrow(datos_filtrados), "\n")
## Total de registros filtrados: 269
resumen_df <- data.frame(
Variable = c("Promedio anual PM2.5 (x, µg/m³)", "Percentil 98 PM2.5 (y, µg/m³)"),
N = c(nrow(datos_filtrados), nrow(datos_filtrados)),
Minimo = c(min(datos_filtrados$Promedio), min(datos_filtrados$Percentil98)),
Mediana = c(median(datos_filtrados$Promedio), median(datos_filtrados$Percentil98)),
Media = c(mean(datos_filtrados$Promedio), mean(datos_filtrados$Percentil98)),
Desv_Estandar = c(sd(datos_filtrados$Promedio), sd(datos_filtrados$Percentil98)),
Maximo = c(max(datos_filtrados$Promedio), max(datos_filtrados$Percentil98))
)
kable(resumen_df, digits = 2, caption = "Estadísticos descriptivos del conjunto filtrado (PM2.5, 24 h, Bogotá, D.C.)")
| Variable | N | Minimo | Mediana | Media | Desv_Estandar | Maximo |
|---|---|---|---|---|---|---|
| Promedio anual PM2.5 (x, µg/m³) | 269 | 7.07 | 16.1 | 17.85 | 5.88 | 36.10 |
| Percentil 98 PM2.5 (y, µg/m³) | 269 | 16.92 | 35.8 | 37.56 | 9.21 | 67.83 |
kable(head(datos_filtrados, 10), digits = 2, caption = "Primeras 10 observaciones filtradas")
| Estacion | Municipio | Anio | Promedio | Percentil98 | Maximo | Representatividad |
|---|---|---|---|---|---|---|
| KENNEDY | BOGOTÁ, D.C. | 2011 | 31.0 | 56.8 | 75.2 | 83 |
| KENNEDY | BOGOTÁ, D.C. | 2012 | 28.3 | 53.5 | 64.8 | 93 |
| KENNEDY | BOGOTÁ, D.C. | 2013 | 28.3 | 48.0 | 54.7 | 98 |
| USAQUÉN | BOGOTÁ, D.C. | 2014 | 13.3 | 33.9 | 46.4 | 84 |
| C. ALTO RENDIMIENTO | BOGOTÁ, D.C. | 2014 | 20.6 | 45.0 | 51.4 | 82 |
| SUBA | BOGOTÁ, D.C. | 2014 | 21.3 | 43.3 | 54.6 | 76 |
| TUNAL | BOGOTÁ, D.C. | 2014 | 22.9 | 50.9 | 62.4 | 95 |
| KENNEDY | BOGOTÁ, D.C. | 2014 | 31.7 | 57.0 | 67.3 | 89 |
| CARVAJAL - SEVILLANA | BOGOTÁ, D.C. | 2014 | 32.6 | 48.6 | 76.9 | 87 |
| SAN CRISTÓBAL | BOGOTÁ, D.C. | 2015 | 8.9 | 22.4 | 32.2 | 90 |
Antes de ajustar la recta, se visualiza la dispersión de los puntos para verificar la tendencia lineal entre el promedio anual y el percentil 98.
ggplot(datos_filtrados, aes(x = Promedio, y = Percentil98)) +
geom_point(aes(color = Anio), size = 2.8, alpha = 0.85) +
scale_color_gradient(low = "#0096C7", high = "#023E8A", name = "Año") +
labs(
title = "Relación entre Promedio Anual y Percentil 98 de PM2.5",
subtitle = "Bogotá, D.C. | Exposición 24 horas | Representatividad temporal >= 75%",
x = "Promedio Anual de PM2.5 (µg/m³)",
y = "Percentil 98 de PM2.5 (µg/m³)"
) +
theme_minimal(base_size = 12) +
theme(
plot.title = element_text(face = "bold", color = "#0B3C5D"),
plot.subtitle = element_text(color = "#4A5568"),
panel.grid.minor = element_blank()
)
El modelo estimado por mínimos cuadrados ordinarios (MCO) tiene la forma:
\[\hat{y} = \hat{\beta}_0 + \hat{\beta}_1 x\]
modelo <- lm(Percentil98 ~ Promedio, data = datos_filtrados)
coef(modelo)
## (Intercept) Promedio
## 12.729137 1.391275
summary(modelo)
##
## Call:
## lm(formula = Percentil98 ~ Promedio, data = datos_filtrados)
##
## Residuals:
## Min 1Q Median 3Q Max
## -9.4847 -3.2286 -0.2936 2.4929 11.8018
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 12.72914 0.82721 15.39 <2e-16 ***
## Promedio 1.39127 0.04402 31.60 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 4.238 on 267 degrees of freedom
## Multiple R-squared: 0.7891, Adjusted R-squared: 0.7883
## F-statistic: 998.7 on 1 and 267 DF, p-value: < 2.2e-16
res_coef <- as.data.frame(summary(modelo)$coefficients)
colnames(res_coef) <- c("Estimacion", "Error_Estandar", "Estadistico_t", "Valor_p")
res_coef$R2 <- summary(modelo)$r.squared
res_coef$R2_Ajustado <- summary(modelo)$adj.r.squared
kable(res_coef, digits = 4, caption = "Parámetros estimados y bondad de ajuste del modelo lineal")
| Estimacion | Error_Estandar | Estadistico_t | Valor_p | R2 | R2_Ajustado | |
|---|---|---|---|---|---|---|
| (Intercept) | 12.7291 | 0.8272 | 15.3881 | 0 | 0.7891 | 0.7883 |
| Promedio | 1.3913 | 0.0440 | 31.6027 | 0 | 0.7891 | 0.7883 |
b0 <- coef(modelo)[1]
b1 <- coef(modelo)[2]
r2 <- summary(modelo)$r.squared
ecuacion_txt <- sprintf("ŷ = %.2f + %.2fx (R² = %.2f)", b0, b1, r2)
ggplot(datos_filtrados, aes(x = Promedio, y = Percentil98)) +
geom_point(color = "#0077B6", fill = "#90E0EF", shape = 21, size = 3, alpha = 0.85) +
geom_smooth(method = "lm", se = TRUE, color = "#D62828", fill = "#F4A261", alpha = 0.22, linewidth = 1.3) +
annotate(
"label",
x = min(datos_filtrados$Promedio) + 1.5,
y = max(datos_filtrados$Percentil98) * 0.94,
label = ecuacion_txt,
hjust = 0,
fill = "#FFF8F0",
color = "#9B2226",
fontface = "bold",
size = 4
) +
labs(
title = "Regresión Lineal: Promedio Anual vs. Percentil 98 de PM2.5",
subtitle = "Recta ajustada por mínimos cuadrados con banda de confianza del 95% (Bogotá, D.C.)",
x = "Promedio Anual de PM2.5 (µg/m³)",
y = "Percentil 98 de PM2.5 (µg/m³)",
caption = "Elaboración propia a partir de datos oficiales de calidad del aire en Colombia."
) +
theme_classic(base_size = 12) +
theme(
plot.title = element_text(face = "bold", color = "#0B3C5D", size = 14),
plot.subtitle = element_text(color = "#334E68"),
plot.caption = element_text(color = "#627D98", face = "italic")
)