En esta sección se cargan las librerías necesarias para el análisis.
# install.packages(c("readxl", "dplyr", "gt", "ggplot2", "scales", "forcats"))
library(readxl)
library(dplyr)
library(gt)
library(ggplot2)
library(scales)
library(forcats)
Se importa el dataset Global Oil and Gas Extraction Tracker (GOGET), que contiene registros de unidades de extracción de petróleo y gas a nivel mundial.
# El archivo debe estar en el directorio de trabajo
datos <- read_excel("C:/Users/DELL/OneDrive/Nueva carpeta/Estadistica/dataset_mundial_petro.xlsx")
cat("Número de registros:", nrow(datos), "\n")
## Número de registros: 49212
cat("Número de variables:", ncol(datos), "\n")
## Número de variables: 32
Se selecciona la variable Location accuracy del dataset y se realiza la limpieza correspondiente: traducción de categorías al español, eliminación de valores nulos y ordenamiento según el nivel de precisión (de mayor a menor exactitud).
n <- nrow(datos)
# Orden lógico según el nivel de precisión
orden_logico <- c("exact", "approximate")
orden_esp <- c("Exacto", "Aproximado")
# Extraer y limpiar
Variable <- datos$`Location accuracy`
Variable <- Variable[!is.na(Variable)]
cat("Registros con dato:", length(Variable), "\n")
## Registros con dato: 7538
cat("Registros sin dato (NA):", n - length(Variable), "\n")
## Registros sin dato (NA): 41674
# Recodificar al español
Variable_esp <- recode(Variable,
"exact" = "Exacto",
"approximate" = "Aproximado"
)
# Aplicar orden lógico
Variable_esp <- factor(Variable_esp, levels = orden_esp, ordered = TRUE)
Se calcula la frecuencia absoluta (ni), la frecuencia relativa en proporción (hi) y en porcentaje (hi %) para cada categoría, ordenadas de mayor a menor.
tabla_freq <- as.data.frame(table(Variable_esp)) %>%
rename(Precision = Variable_esp, ni = Freq) %>%
arrange(desc(ni)) %>%
mutate(
Precision = as.character(Precision),
ni = as.numeric(ni),
hi_prop = ni / length(Variable),
hi_pct = hi_prop * 100,
i = row_number()
) %>%
select(i, Precision, ni, hi_pct, hi_prop)
k <- nrow(tabla_freq)
cat("Número de categorías (k):", k, "\n")
## Número de categorías (k): 2
cat("Categoría más frecuente :", tabla_freq$Precision[1],
"-", tabla_freq$ni[1], "registros\n")
## Categoría más frecuente : Exacto - 6353 registros
cat("Categoría menos frecuente:", tabla_freq$Precision[k],
"-", tabla_freq$ni[k], "registro(s)\n")
## Categoría menos frecuente: Aproximado - 1185 registro(s)
cat("Verificación - Σni:", sum(tabla_freq$ni),
"(debe ser", length(Variable), ")\n")
## Verificación - Σni: 7538 (debe ser 7538 )
cat("Verificación - Σhi%:", round(sum(tabla_freq$hi_pct)), "(debe ser 100)\n")
## Verificación - Σhi%: 100 (debe ser 100)
# Construir TDF en orden lógico
conteo <- as.data.frame(table(Variable_esp)) %>%
rename(Precision = Variable_esp, ni = Freq) %>%
mutate(
Precision = as.character(Precision),
ni = as.numeric(ni),
hi_prop = round(ni / sum(ni), 3),
hi_pct = round(ni / sum(ni) * 100, 2)
)
# Fila total
fila_total <- tibble(
Precision = "TOTAL",
ni = sum(conteo$ni),
hi_prop = sum(conteo$hi_prop),
hi_pct = sum(conteo$hi_pct)
)
tdf_final <- bind_rows(conteo, fila_total)
tdf_final %>%
gt() %>%
tab_header(
title = md("**Tabla N° 1**"),
subtitle = md("Distribución de yacimientos según precisión de ubicación")
) %>%
cols_label(
Precision = "Nivel de Precisión",
ni = "ni",
hi_prop = "(proporción)",
hi_pct = "(%)"
) %>%
tab_spanner(
label = md("**hi**"),
columns = c(hi_prop, hi_pct)
) %>%
fmt_number(columns = hi_prop, decimals = 3) %>%
fmt_number(columns = hi_pct, decimals = 2) %>%
fmt_integer(columns = ni) %>%
tab_source_note(source_note = "Autor: Grupo 5") %>%
cols_align(align = "center", columns = everything()) %>%
tab_style(
style = list(cell_text(weight = "bold"),
cell_borders(sides = "top", color = "black", weight = px(2))),
locations = cells_body(rows = nrow(tdf_final))
) %>%
tab_options(
table.border.top.color = "black",
table.border.bottom.color = "black",
table.border.top.style = "solid",
table.border.bottom.style = "solid",
column_labels.font.weight = "bold",
column_labels.border.top.color = "black",
column_labels.border.bottom.color = "black",
column_labels.border.bottom.width = px(2),
heading.border.bottom.color = "black",
heading.border.bottom.width = px(2),
table_body.hlines.color = "grey",
table_body.border.bottom.color = "black"
)
| Tabla N° 1 | |||
| Distribución de yacimientos según precisión de ubicación | |||
| Nivel de Precisión | ni |
hi
|
|
|---|---|---|---|
| (proporción) | (%) | ||
| Exacto | 6,353 | 0.843 | 84.28 |
| Aproximado | 1,185 | 0.157 | 15.72 |
| TOTAL | 7,538 | 1.000 | 100.00 |
| Autor: Grupo 5 | |||
# Datos para gráficos (sin fila TOTAL)
conteo_graf <- conteo
conteo_graf$Precision <- factor(conteo_graf$Precision, levels = orden_esp)
# Colores por categoría
colores <- c("Exacto" = "#2E86C1", "Aproximado" = "#AED6F1")
ggplot(conteo_graf, aes(x = Precision, y = ni, fill = Precision)) +
geom_col(width = 0.5, color = "white", linewidth = 0.3) +
geom_text(
aes(label = format(ni, big.mark = ",")),
vjust = -0.4, size = 3.2, color = "#222222", fontface = "bold"
) +
scale_fill_manual(values = colores) +
scale_y_continuous(
labels = label_comma(),
expand = expansion(mult = c(0, 0.2))
) +
labs(
title = "Gráfica N°1: Distribución de yacimientos por Precisión de Ubicación",
x = "Nivel de Precisión",
y = "Frecuencia Absoluta (ni)",
caption = paste0("n = ", format(n, big.mark = ","),
" | Fuente: Global Energy Monitor — GOGET")
) +
theme_minimal(base_size = 12) +
theme(
legend.position = "none",
plot.title = element_text(face = "bold", color = "#222222", size = 12),
axis.title = element_text(face = "bold", color = "#333333"),
axis.text.x = element_text(color = "#333333"),
axis.text.y = element_text(color = "#333333"),
panel.grid.major.x = element_blank(),
panel.grid.major.y = element_line(color = "#EEEEEE"),
plot.background = element_rect(fill = "white", color = NA),
panel.background = element_rect(fill = "white", color = NA)
)
ggplot(conteo_graf, aes(x = Precision, y = hi_pct, fill = Precision)) +
geom_col(width = 0.5, color = "white", linewidth = 0.3) +
geom_text(
aes(label = paste0(hi_pct, "%")),
vjust = -0.4, size = 3.2, color = "#222222", fontface = "bold"
) +
scale_fill_manual(values = colores) +
scale_y_continuous(
labels = function(x) paste0(x, "%"),
expand = expansion(mult = c(0, 0.2))
) +
labs(
title = "Gráfica N°2: Distribución porcentual por Precisión de Ubicación",
x = "Nivel de Precisión",
y = "Frecuencia Relativa (%)",
caption = paste0("n = ", format(n, big.mark = ","),
" | Fuente: Global Energy Monitor — GOGET")
) +
theme_minimal(base_size = 12) +
theme(
legend.position = "none",
plot.title = element_text(face = "bold", color = "#222222", size = 12),
axis.title = element_text(face = "bold", color = "#333333"),
axis.text.x = element_text(color = "#333333"),
axis.text.y = element_text(color = "#333333"),
panel.grid.major.x = element_blank(),
panel.grid.major.y = element_line(color = "#EEEEEE"),
plot.background = element_rect(fill = "white", color = NA),
panel.background = element_rect(fill = "white", color = NA)
)
datos_pie <- conteo_graf %>%
arrange(desc(ni)) %>%
mutate(
Precision = fct_reorder(Precision, hi_pct),
# Solo mostrar etiqueta si el sector es suficientemente grande
etiqueta = ifelse(hi_pct >= 2, paste0(round(hi_pct, 1), "%"), "")
)
# Paleta que va de oscuro (mayor valor) a claro (menor valor)
n_cats <- nrow(datos_pie)
paleta_pie <- colorRampPalette(c("#AED6F1", "#1A5276"))(n_cats)
names(paleta_pie) <- levels(datos_pie$Precision)
ggplot(datos_pie, aes(x = "", y = hi_pct, fill = Precision)) +
geom_col(width = 1, color = "white", linewidth = 0.6) +
geom_text(
aes(label = etiqueta),
position = position_stack(vjust = 0.5),
size = 3.5, color = "white", fontface = "bold"
) +
coord_polar(theta = "y", start = 0) +
scale_fill_manual(values = paleta_pie) +
labs(
title = "Gráfica N°3: Distribución Porcentual por Precisión de Ubicación",
fill = "Nivel de Precisión",
caption = paste0("n = ", format(n, big.mark = ","),
" | Fuente: Global Energy Monitor — GOGET")
) +
theme_void(base_size = 12) +
theme(
plot.title = element_text(face = "bold", color = "#222222",
size = 12, hjust = 0.5),
plot.caption = element_text(color = "#888888", size = 9),
legend.position = "right",
legend.title = element_text(face = "bold", color = "#222222"),
legend.text = element_text(size = 8, color = "#333333"),
plot.background = element_rect(fill = "white", color = NA)
)
Para variables cualitativas únicamente se calcula la Moda, ya que la media, mediana y demás indicadores numéricos no aplican sobre categorías.
moda <- conteo$Precision[which.max(conteo$ni)]
tabla_ind <- data.frame(
"Variable" = "Location accuracy",
"Escala" = "Ordinal",
"Rango" = "Precisión de la ubicación (exacto → aproximado)",
"Media (X)" = "-",
"Mediana (Me)" = "-",
"Moda (Mo)" = moda,
"Varianza (V)" = "-",
"Desv. Est. (Sd)" = "-",
"C.V. (%)" = "-",
"Asimetría (As)" = "-",
"Curtosis (K)" = "-",
check.names = FALSE
)
tabla_ind %>%
gt() %>%
tab_header(
title = md("**Tabla N°2: Indicadores Estadísticos**"),
subtitle = md("Variable: Precisión de Ubicación (Location Accuracy)")
) %>%
tab_source_note(source_note = "Autor: Grupo 5") %>%
cols_align(align = "center", columns = everything()) %>%
tab_options(
table.border.top.color = "black",
table.border.bottom.color = "black",
table.border.top.style = "solid",
table.border.bottom.style = "solid",
column_labels.font.weight = "bold",
column_labels.border.top.color = "black",
column_labels.border.bottom.color = "black",
column_labels.border.bottom.width = px(2),
heading.border.bottom.color = "black",
heading.border.bottom.width = px(2),
table_body.hlines.color = "grey",
table_body.border.bottom.color = "black"
)
| Tabla N°2: Indicadores Estadísticos | ||||||||||
| Variable: Precisión de Ubicación (Location Accuracy) | ||||||||||
| Variable | Escala | Rango | Media (X) | Mediana (Me) | Moda (Mo) | Varianza (V) | Desv. Est. (Sd) | C.V. (%) | Asimetría (As) | Curtosis (K) |
|---|---|---|---|---|---|---|---|---|---|---|
| Location accuracy | Ordinal | Precisión de la ubicación (exacto → aproximado) | - | - | Exacto | - | - | - | - | - |
| Autor: Grupo 5 | ||||||||||
Los valores de location accurary fluctúan entre Exacto y Aproximado y giran en torno a Exacto.