En este primer paso, se prepara el entorno de trabajo cargando las
librerías necesarias para la manipulación de datos (dplyr),
la creación de visualizaciones avanzadas (ggplot2), y el
formato profesional de tablas (gt).
library(readxl)
library(dplyr)
library(gt)
library(ggplot2)
# Se abre ventana emergente para seleccionar dinámicamente el dataset
ruta_archivo <- file.choose()
datos_originales <- read_excel(ruta_archivo)
cat("Dataset cargado exitosamente. Total de variables:", ncol(datos_originales), "\n")## Dataset cargado exitosamente. Total de variables: 32
Se aísla la variable de interés (Status) y se eliminan
los registros nulos (NA). Esto garantiza que el análisis de
frecuencias y los porcentajes reflejen exclusivamente aquellos
yacimientos que cuentan con un estado operativo oficialmente
reportado.
Por requerimiento analítico, los datos sí serán ordenados de mayor a menor frecuencia para identificar la concentración del mercado.
tdf_unidades <- datos_originales %>%
select(`Status`) %>%
filter(!is.na(`Status`)) %>%
mutate(Categoria = trimws(as.character(`Status`))) %>%
group_by(Categoria) %>%
summarise(Fi = n()) %>%
arrange(desc(Fi)) %>%
mutate(
hi = Fi / sum(Fi),
Pi = hi * 100,
Fi_ac = cumsum(Fi),
hi_ac = cumsum(hi)
)
N <- sum(tdf_unidades$Fi)
cat("Variable analizada: Status\n")## Variable analizada: Status
## Total de observaciones limpias (N): 8068
La tabla se estructura ordenando las categorías por su frecuencia absoluta de mayor a menor. Las frecuencias acumuladas permiten evaluar rápidamente qué porcentaje del portafolio global se encuentra aglomerado en las fases operativas más frecuentes.
# Fila de totales
fila_total <- data.frame(
Categoria = "TOTAL",
Fi = sum(tdf_unidades$Fi),
hi = sum(tdf_unidades$hi),
Pi = sum(tdf_unidades$Pi),
Fi_ac = NA,
hi_ac = NA
)
TDF_Final <- bind_rows(tdf_unidades %>% mutate(Categoria = as.character(Categoria)), fila_total)
fuente_nota <- paste("Fuente: Global Energy Monitor — GOGET 2023 | n =", format(N, big.mark = ","))
TDF_Final %>%
gt() %>%
tab_header(
title = md("**TABLA 1. Distribución de Frecuencias por Estado Operativo**")
) %>%
cols_label(
Categoria = "Estado (Status)",
Fi = md("Frec. Absoluta<br>(Fi)"),
hi = md("Frec. Relativa<br>(hi)"),
Pi = md("Porcentaje<br>(%)"),
Fi_ac = md("Frec. Abs.<br>Acumulada (Fi_ac)"),
hi_ac = md("Frec. Rel.<br>Acumulada (hi_ac)")
) %>%
cols_align(align = "center", columns = everything()) %>%
fmt_number(columns = c(hi, hi_ac), decimals = 5) %>%
fmt_number(columns = c(Pi), decimals = 2) %>%
fmt_number(columns = c(Fi, Fi_ac), decimals = 0, use_seps = TRUE) %>%
sub_missing(columns = everything(), missing_text = "") %>%
tab_source_note(fuente_nota) %>%
tab_style(
style = cell_fill(color = "#F5F5F5"),
locations = cells_body(rows = nrow(TDF_Final))
) %>%
tab_style(
style = cell_text(weight = "bold"),
locations = cells_body(rows = nrow(TDF_Final))
) %>%
tab_options(heading.background.color = "#EBF5FB", column_labels.font.weight = "bold")| TABLA 1. Distribución de Frecuencias por Estado Operativo | |||||
| Estado (Status) | Frec. Absoluta (Fi) |
Frec. Relativa (hi) |
Porcentaje (%) |
Frec. Abs. Acumulada (Fi_ac) |
Frec. Rel. Acumulada (hi_ac) |
|---|---|---|---|---|---|
| operating | 6,351 | 0.78718 | 78.72 | 6,351 | 0.78718 |
| shut in | 990 | 0.12271 | 12.27 | 7,341 | 0.90989 |
| discovered | 396 | 0.04908 | 4.91 | 7,737 | 0.95897 |
| in development | 233 | 0.02888 | 2.89 | 7,970 | 0.98785 |
| decommissioned | 71 | 0.00880 | 0.88 | 8,041 | 0.99665 |
| abandoned | 13 | 0.00161 | 0.16 | 8,054 | 0.99826 |
| UGS | 11 | 0.00136 | 0.14 | 8,065 | 0.99963 |
| cancelled | 2 | 0.00025 | 0.02 | 8,067 | 0.99988 |
| exploration | 1 | 0.00012 | 0.01 | 8,068 | 1.00000 |
| TOTAL | 8,068 | 1.00000 | 100.00 | ||
| Fuente: Global Energy Monitor — GOGET 2023 | n = 8,068 | |||||
# Paleta de colores dinámica ajustada automáticamente al número de estados
paleta_azul <- colorRampPalette(c("#08519c", "#3182bd", "#6baed6", "#9ecae1", "#c6dbef"))(nrow(tdf_unidades))ggplot(tdf_unidades, aes(x = reorder(Categoria, -Fi), y = Fi, fill = Categoria)) +
geom_bar(stat = "identity", show.legend = FALSE, color = "black", size = 0.3) +
geom_text(aes(label = format(Fi, big.mark = ",")), vjust = -0.5, size = 3.5, fontface = "bold") +
scale_fill_manual(values = paleta_azul) +
theme_minimal() +
labs(x = "Estado Operativo", y = "Frecuencia Absoluta (Fi)") +
theme(
plot.title = element_blank(),
axis.title = element_text(size = 12, face = "bold"),
axis.text = element_text(size = 10),
axis.text.x = element_text(angle = 45, hjust = 1)
) +
scale_y_continuous(expand = expansion(mult = c(0, 0.15)))ggplot(tdf_unidades, aes(x = reorder(Categoria, -Pi), y = Pi, fill = Categoria)) +
geom_bar(stat = "identity", show.legend = FALSE, color = "black", size = 0.3) +
geom_text(aes(label = paste0(round(Pi, 1), "%")), vjust = -0.5, size = 3.5, fontface = "bold") +
scale_fill_manual(values = paleta_azul) +
theme_minimal() +
labs(x = "Estado Operativo", y = "Porcentaje (%)") +
theme(
plot.title = element_blank(),
axis.title = element_text(size = 12, face = "bold"),
axis.text = element_text(size = 10),
axis.text.x = element_text(angle = 45, hjust = 1)
) +
scale_y_continuous(expand = expansion(mult = c(0, 0.15)))# Preparación de etiquetas para leyenda
plot_data <- tdf_unidades %>%
mutate(label_leyenda = paste0(Categoria, " (", round(Pi, 1), "%)"))
ggplot(plot_data, aes(x = "", y = Pi, fill = reorder(label_leyenda, -Pi))) +
geom_bar(stat = "identity", width = 1, color = "white", size = 0.5) +
coord_polar("y", start = 0) +
scale_fill_manual(values = paleta_azul) +
theme_void() +
theme(
legend.position = "right",
legend.text = element_text(size = 11),
legend.title = element_text(face = "bold", size = 12),
plot.margin = margin(t = 20, r = 20, b = 20, l = 20)
) +
guides(fill = guide_legend(title = "Estado (Status)"))# Cálculos de indicadores
num_categorias <- nrow(tdf_unidades)
moda_cat <- as.character(tdf_unidades$Categoria[1])
moda_ni <- tdf_unidades$Fi[1]
moda_hi <- round(tdf_unidades$Pi[1], 2)
tabla_ind <- data.frame(
"Total Registros (N)" = format(N, big.mark = ","),
"Fases/Estados Diferentes" = num_categorias,
"Estado Predominante (Moda)" = moda_cat,
"Frecuencia de la Moda" = format(moda_ni, big.mark = ","),
"Peso de la Moda" = paste0(moda_hi, "%"),
check.names = FALSE
)
tabla_ind %>%
gt() %>%
tab_header(
title = md("**TABLA 2. Indicadores Estadísticos Globales**")
) %>%
cols_align(align = "center", columns = everything()) %>%
tab_source_note("Autor: Grupo 5") %>%
tab_options(heading.background.color = "#EBF5FB", column_labels.font.weight = "bold")| TABLA 2. Indicadores Estadísticos Globales | ||||
| Total Registros (N) | Fases/Estados Diferentes | Estado Predominante (Moda) | Frecuencia de la Moda | Peso de la Moda |
|---|---|---|---|---|
| 8,068 | 9 | operating | 6,351 | 78.72% |
| Autor: Grupo 5 | ||||