#Estadística Descriptiva
#Variable Cualitativa Ordinal
#Autor: Ariana Viteri
#Fecha:24/05/2026

0.- Carga de Librerias

# ================================
# LIBRERÍAS
# ================================
library(gt)
## Warning: package 'gt' was built under R version 4.5.3
library(dplyr)
## Warning: package 'dplyr' was built under R version 4.5.3
## 
## 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(RColorBrewer)

1.- Carga de Datos

# ===== CARGA DE DATOS =====
datos <- read.csv("~/semestre 3 y 4/Estadistica/Datos Cambiados.csv",
                  header = TRUE, dec = ".", sep = ",")

2.- Selecionar la variable

datos <- datos[datos$AQI_Bucket != "-" & !is.na(datos$AQI_Bucket), ]

# ================================
# ORDEN JERÁRQUICO (IMPORTANTE)
# ================================
datos$AQI_Bucket <- factor(
  datos$AQI_Bucket,
  levels = c("Good", "Satisfactory", "Moderate",
             "Poor", "Very Poor", "Severe"),
  ordered = TRUE
)

3.- Frecuencia

# ================================
# FRECUENCIA RESPETANDO ORDEN
# ================================
TDF_AQI_Bucket <- datos %>%
  group_by(AQI_Bucket) %>%
  summarise(ni = n()) %>%
  arrange(AQI_Bucket)

# frecuencia relativa
TDF_AQI_Bucket$hi <- round((TDF_AQI_Bucket$ni / sum(TDF_AQI_Bucket$ni)) * 100, 2)

# ================================
# TOTAL
# ================================
Summary <- data.frame(
  AQI_Bucket = "TOTAL",
  ni = sum(TDF_AQI_Bucket$ni),
  hi = 100
)

# ================================
# TABLA FINAL
# ================================
TDF_AQI_Bucket_suma <- rbind(TDF_AQI_Bucket, Summary)

TDF_AQI_Bucket_suma

4.- Tabla de distribución de frecuencia

# TABLA 
TDF_AQI_Bucket_suma %>%
  gt() %>%
  tab_header(
    title = md("Tabla Nro. 1"),
    subtitle = md("Distribución de frecuencias de AQI_Bucket en el estudio calidad del aire en India de 2015-2020")
  ) %>%
  tab_source_note(
    source_note = md("Grupo: 1 <br> Fuente: https://www.kaggle.com/datasets/rohanrao/air-quality-data-in-india ")
  ) %>%
  tab_style(
    style = cell_borders(sides = "left", color = "black", weight = px(2)),
    locations = cells_body()
  ) %>%
  tab_style(
    style = cell_borders(sides = "right", color = "black", weight = px(2)),
    locations = cells_body()
  ) %>%
  tab_style(
    style = cell_borders(sides = "left", color = "black", weight = px(2)),
    locations = cells_column_labels()
  ) %>%
  tab_style(
    style = cell_borders(sides = "right", color = "black", weight = px(2)),
    locations = cells_column_labels()
  ) %>%
  tab_options(
    table.border.top.color = "black",
    table.border.bottom.color = "black",
    table.border.top.style = "solid",
    table.border.bottom.style = "solid",
    column_labels.border.top.color = "black",
    column_labels.border.bottom.color = "black",
    column_labels.border.bottom.width = px(2),
    row.striping.include_table_body = TRUE,
    heading.border.bottom.color = "black",
    heading.border.bottom.width = px(2),
    table_body.hlines.color = "gray",
    table_body.border.bottom.color = "black"
  )
Tabla Nro. 1
Distribución de frecuencias de AQI_Bucket en el estudio calidad del aire en India de 2015-2020
AQI_Bucket ni hi
Good 1341 5.40
Satisfactory 8224 33.09
Moderate 8829 35.53
Poor 2781 11.19
Very Poor 2337 9.40
Severe 1338 5.38
TOTAL 24850 100.00
Grupo: 1
Fuente: https://www.kaggle.com/datasets/rohanrao/air-quality-data-in-india

5.- Gráfico de distribución de frecuencia

Diagramas de Cantidad

#===========================
# Diagrama de barra que genera R studio

library(RColorBrewer)

# Colores suaves
n <- length(TDF_AQI_Bucket$AQI_Bucket)
colores <- brewer.pal(min(max(n,3), 8), "Set2")
par(mar = c(6, 7, 4, 2))
# Crear gráfico
barplot(
  height = TDF_AQI_Bucket$ni,
  names.arg = TDF_AQI_Bucket$AQI_Bucket,
  
  # Títulos
  main = "Gráfica Nro. 1\nDistribución de AQI_Bucket en el estudio\ncalidad del aire en India (2015-2020)",
  ylab = "Cantidad",
  
  # Diseño
  col = colores,
  border = "white",
  
  # Texto
  las = 2,
  cex.names = 0.9,
  cex.main = 1,
  cex.lab = 1,
  
  # Tamaño barras
  width = 0.7,
  
  # Espaciado
  space = 0.3
)
title(xlab = "AQI_Bucket", line = 5)
# Líneas de fondo
grid(
  nx = NA,
  ny = NULL,
  col = "gray80",
  lty = 1
)

#================================
# Diagrama de barras con relación a la totalidad de los datos

library(RColorBrewer)
# Colores suaves
n <- length(TDF_AQI_Bucket$AQI_Bucket)
colores <- brewer.pal(min(max(n,3), 8), "Set2")
par(mar = c(6, 5, 5, 5))
# Valor máximo
max_y_global <- max(TDF_AQI_Bucket$ni) + 500

# Crear gráfico
barplot(
  height = TDF_AQI_Bucket$ni,
  
  # Etiquetas
  names.arg = TDF_AQI_Bucket$AQI_Bucket,
  
  # Títulos
  main = "Gráfica Nro. 2\nDistribución de AQI_Bucket en el estudio\ncalidad del aire en India (2015-2020)",
  
  # Diseño
  col = colores,
  border = "white",
  
  # Escala
  ylim = c(0,25000),
  
  # Texto
  las = 2,
  cex.names = 0.9,
  cex.main = 1,
  cex.lab = 1,
  
  # Barras
  width = 0.7,
  space = 0.3
)

title(
  xlab = "AQI_Bucket",
  line = 4.5
)

title(
  ylab = "Cantidad",
  line = 4
)
# Líneas de fondo
grid(
  nx = NA,
  ny = NULL,
  col = "gray80",
  lty = 1
)

Diagrama Porcentual

# ================================
#Diagrama de barras que genera r studio porcentual

library(RColorBrewer)
par(mar = c(6, 5, 5, 5))
# Colores suaves
n <- length(TDF_AQI_Bucket$AQI_Bucket)
colores <- brewer.pal(min(max(n,3), 8), "Set2")

# Crear gráfico
barplot(
  TDF_AQI_Bucket$hi,
  
  # Etiquetas
  names.arg = TDF_AQI_Bucket$AQI_Bucket,
  
  # Títulos
  main = "Gráfica Nro. 3\nDistribución de frecuencia AQI_Bucket en el estudio\ncalidad del aire en India (2015-2020)",
  
  ylab = "Porcentaje",
  
  # Diseño
  col = colores,
  border = "white",
  
  # Escala
  ylim = c(0, max(TDF_AQI_Bucket$hi) + 5),
  
  # Texto
  las = 2,
  cex.names = 0.9,
  cex.main = 1,
  cex.lab = 1,
  
  # Barras
  width = 0.7,
  space = 0.3
)

# Bajar nombre del eje X
title(xlab = "AQI_Bucket", line = 5)

# Líneas de fondo
grid(
  nx = NA,
  ny = NULL,
  col = "gray80",
  lty = 1
)

# ================================
# Diagrama de barras con relación a la totalidad porcentualmente

library(RColorBrewer)

# Colores suaves
n <- length(TDF_AQI_Bucket$AQI_Bucket)
colores <- brewer.pal(min(max(n,3), 8), "Set2")
par(mar = c(6, 7, 4, 2))
# Crear gráfico
barplot(
  TDF_AQI_Bucket$hi,
  
  # Etiquetas
  names.arg = TDF_AQI_Bucket$AQI_Bucket,
  
  # Títulos
  main = "Gráfica Nro. 4\nDistribución de frecuencia de AQI_Bucket en el estudio\ncalidad del aire en India (2015-2020)",
  
  ylab = "Porcentaje",
  
  # Diseño
  col = colores,
  border = "white",
  
  # Escala
  ylim = c(0, 100),
  
  # Texto
  las = 2,
  cex.names = 0.9,
  cex.main = 1,
  cex.lab = 1,
  
  # Barras
  width = 0.7,
  space = 0.3
)

# Bajar nombre eje X
title(xlab = "AQI_Bucket", line = 5)

# Líneas de fondo
grid(
  nx = NA,
  ny = NULL,
  col = "gray80",
  lty = 1
)

Diagrama Circular

# ================================
# DIAGRAMA CIRCULAR

library(RColorBrewer)

# Colores pastel suaves
colores <- c(
  "#FBB4AE",  # rosado pastel
  "#FFF2AE",  # amarillo pastel
  "#CDEAC0",  # verde pastel
  "#B5D8EB",  # celeste pastel
  "#E4C1F9",  # lila pastel
  "#FFD6A5"   # naranja pastel
)

color <- adjustcolor(colores, alpha.f = 0.95)

# Etiquetas porcentuales
etiqueta <- paste0(TDF_AQI_Bucket$hi, " %")

# Crear gráfico circular
pie(
  TDF_AQI_Bucket$hi,
  
  labels = etiqueta,
  
  radius = 0.9,
  
  col = color,
  
  # Bordes marcados
  border = "black",
  lwd = 2,
  
  main = "Gráfica Nro. 5\nDistribución de AQI_Bucket en el estudio\ncalidad del aire en India (2015-2020)",
  
  cex.main = 1,
  cex = 0.9
)

# Leyenda
legend(
  "topright",
  
  legend = TDF_AQI_Bucket$AQI_Bucket,
  
  title = "Leyenda",
  
  fill = color,
  
  border = "black",
  
  box.lwd = 1,
  box.col = "black",
  
  cex = 0.7,
  
  bty = "o"
)

6.- Indicadores Estadísticos

# =========================================================
# INDICADORES ESTADÍSTICOS para la variable AQI_Bucket (Cualitativa Ordinal)

# 1. CÁLCULO DE LA MODA (Mo)
# Es el nivel con la mayor frecuencia (ni)
Moda_row <- TDF_AQI_Bucket[which.max(TDF_AQI_Bucket$ni), ]
Mo_calc <- as.character(Moda_row$AQI_Bucket[1])

# 2. CÁLCULO DE LA MEDIANA (Me)
# Frecuencias Acumuladas
Ni_calc <- cumsum(TDF_AQI_Bucket$ni)
N_total <- sum(TDF_AQI_Bucket$ni)
Posicion_Me <- N_total / 2
# Categoría que contiene la posición N/2
Mediana_row_index <- which(Ni_calc >= Posicion_Me)[1]
Me_calc <- as.character(TDF_AQI_Bucket$AQI_Bucket[Mediana_row_index])

# RANGO CORRECTO (VARIABLE ORDINAL)
# ================================
niveles <- levels(datos$AQI_Bucket)
Rango_calc <- paste0(
  niveles[1],
  " a ",
  niveles[length(niveles)]
)
Rango <- Rango_calc

Variable <- "AQI_Bucket (Nivel de Calidad del Aire)"
# Mediana
Me <- Me_calc # Mediana calculada
# Media
X <- "-"
# Moda
Mo <- Mo_calc # Moda calculada

# Indicadores de Dispersión
# Desviación estandar
desv<-"-"
# Coeficiente de variación 
CV <- "-"

# Indicadores de Forma
# Coeficiente de Asimetría
As <-"-"
# Curtosis
K <- "-"

Tabla de Indicadores

# Crear el Data Frame
Tabla_indicadores <- data.frame(Variable, Rango, X, Me, Mo, desv, CV, As, K)
colnames(Tabla_indicadores) <- c("Variable","Rango","X", "Me", "Mo",
                                 "sd","CV","As","K")

library(gt)
library(dplyr)
# Generar la Tabla GT
Tabla_indicadores %>%
  gt() %>%
  
  tab_header(
    title = md("*Tabla Nro. 2*"),
    subtitle = md("**Indicadores Estadísticos de la variable AQI_Bucket en India entre 2015-2020**")
  ) %>%
  
  tab_source_note(
    source_note = md("Grupo: 1 <br> Fuente: https://www.kaggle.com/datasets/rohanrao/air-quality-data-in-india ")
  ) %>%
  
  # Líneas verticales en TODA la tabla
  tab_style(
    style = cell_borders(
      sides = "left",
      color = "black",
      weight = px(2)
    ),
    locations = list(
      cells_body(),
      cells_column_labels()
    )
  ) %>%
  
  tab_style(
    style = cell_borders(
      sides = "right",
      color = "black",
      weight = px(2)
    ),
    locations = list(
      cells_body(),
      cells_column_labels()
    )
  ) %>%
  
  tab_options(
    table.border.top.color = "black",
    table.border.bottom.color = "black",
    table.border.top.style = "solid",
    table.border.bottom.style = "solid",
    
    column_labels.border.top.color = "black",
    column_labels.border.bottom.color = "black",
    column_labels.border.bottom.width = px(2),
    
    row.striping.include_table_body = TRUE,
    
    heading.border.bottom.color = "black",
    heading.border.bottom.width = px(2),
    
    table_body.hlines.color = "gray",
    table_body.border.bottom.color = "black"
  )
Tabla Nro. 2
Indicadores Estadísticos de la variable AQI_Bucket en India entre 2015-2020
Variable Rango X Me Mo sd CV As K
AQI_Bucket (Nivel de Calidad del Aire) Good a Severe - Moderate Moderate - - - -
Grupo: 1
Fuente: https://www.kaggle.com/datasets/rohanrao/air-quality-data-in-india

7.- Conclusión

En conclusión:

El valor mas frecuente de la variable AQI Bucket es moderate y gira entorno a la mediana moderate, por lo tanto el comportamiento es medianamente malo para el medio ambiente.