knitr::opts_chunk$set(echo = TRUE)
setwd("C:/Users/LEO/Documents/ESTA")
Datos <- read.csv("tabela_de_pocos_janeiro_2018.csv", header = TRUE, sep = ";" , dec = ".", fileEncoding = "Latin1")

1 Introducción y Metodología

El presente informe estadístico analiza la variable Profundidad del Sondador de pozos petroleros de Brasil.

# 1. LIBRERÍAS Y CARGA DE DATOS
library(readxl)
library(dplyr)
library(gt)
library(e1071)

# Carga de datos
Datos_Brutos <- read_xlsx("C:/Users/LEO/Documents/ESTA/tabela_de_pocos_janeiro_2018.xlsx", sheet = 1)
colnames(Datos_Brutos) <- trimws(colnames(Datos_Brutos))

# Cambio de variable a PROFUNDIDADE_SONDADOR_M
Datos <- Datos_Brutos %>%
  select(any_of(c("POCO", "PROFUNDIDADE_SONDADOR_M"))) %>%
  mutate(Variable_Analisis = as.numeric(gsub(",", ".", as.character(PROFUNDIDADE_SONDADOR_M))))

Variable <- na.omit(Datos$Variable_Analisis)
Variable <- Variable[Variable > 0 & Variable < 15000]

if(length(Variable) == 0) {
  stop("ERROR: No hay datos válidos para la variable seleccionada.")
}

# 2. CÁLCULOS MATEMÁTICOS PARA LA TABLA
N <- length(Variable)
K <- floor(1 + 3.322 * log10(N)) 
breaks_table <- seq(min(Variable), max(Variable), length.out = K + 1)

# Cálculo de ni usando cut
ni <- as.vector(table(cut(Variable, breaks = breaks_table, include.lowest = TRUE)))

# Cálculo de vectores estadísticos
hi <- (ni / sum(ni)) * 100 
Ni_asc  <- cumsum(ni)
Ni_desc <- rev(cumsum(rev(ni)))
Hi_asc  <- cumsum(hi)
Hi_desc <- rev(cumsum(rev(hi)))

# Creación de la Tabla de Distribución de Frecuencias (TDF)
TDF_Sondador <- data.frame(
  Li = round(breaks_table[1:K], 2), 
  Ls = round(breaks_table[2:(K+1)], 2), 
  MC = round((breaks_table[1:K] + breaks_table[2:(K+1)]) / 2, 2),            
  ni = ni, 
  hi = hi,
  Ni_asc = Ni_asc, 
  Ni_desc = Ni_desc, 
  Hi_asc = Hi_asc, 
  Hi_desc = Hi_desc
)

2 Distribución de Frecuencias

A continuación se presenta la tabla de distribución de frecuencias obtenida para la Profundidad del Sondador.

TDF_Sondador %>%
  gt(rowname_col = "Li") %>% 
  tab_header(
    title = md("**DISTRIBUCIÓN DE FRECUENCIAS: PROFUNDIDAD SONDADOR**"),
    subtitle = md("Variable: **PROFUNDIDADE_SONDADOR_M**")
  ) %>%
  tab_source_note(source_note = "Fuente: Datos ANP 2018") %>%
  
# Nueva estructura limpia para calcular los totales
  grand_summary_rows(
    columns = c(ni, hi),
    fns = list("TOTAL" = ~sum(., na.rm = TRUE))
  ) %>%
  
  # Formateamos números enteros 
  fmt_number(
    columns = c(ni, Ni_asc, Ni_desc),
    decimals = 0,
    use_seps = TRUE
  ) %>%
  
  # Formateamos los porcentajes a 2 decimales 
  fmt_number(
    columns = c(hi, Hi_asc, Hi_desc),
    decimals = 2
  ) %>%
  
  cols_label(
    Ls = "Lím. Sup", MC = "Marca Clase (Xi)", 
    ni = "ni", hi = "hi (%)", 
    Ni_asc = "Ni (Asc)", Ni_desc = "Ni (Desc)",
    Hi_asc = "Hi (Asc)", Hi_desc = "Hi (Desc)"
  ) %>%
  
  tab_stubhead(label = "Lím. Inf") %>% 
  
  # Alineación de datos al centro
  cols_align(align = "center", columns = everything()) %>%
  
  # Alineación del Stub (Lím. Inf y la palabra TOTAL) al centro
  tab_style(
    style = cell_text(align = "center"),
    locations = cells_stub()
  ) %>%
  
  # Estética de los encabezados (Azul oscuro / Verde petróleo con texto blanco)
  tab_style(
    style = list(cell_fill(color = "#1F4E5B"), cell_text(color = "white", weight = "bold")), 
    locations = list(cells_title(), cells_column_labels(), cells_stubhead())
  ) %>%
  
  tab_options(
    table.border.top.style = "none",
    table.border.bottom.color = "#2E4053",
    column_labels.border.bottom.color = "#2E4053",
    data_row.padding = px(6)
  )
DISTRIBUCIÓN DE FRECUENCIAS: PROFUNDIDAD SONDADOR
Variable: PROFUNDIDADE_SONDADOR_M
Lím. Inf Lím. Sup Marca Clase (Xi) ni hi (%) Ni (Asc) Ni (Desc) Hi (Asc) Hi (Desc)
5.00 543.35 274.17 6,150 23.37 6,150 26,312 23.37 100.00
543.35 1081.69 812.52 6,823 25.93 12,973 20,162 49.30 76.63
1081.69 1620.04 1350.87 4,181 15.89 17,154 13,339 65.19 50.70
1620.04 2158.39 1889.21 2,117 8.05 19,271 9,158 73.24 34.81
2158.39 2696.73 2427.56 1,684 6.40 20,955 7,041 79.64 26.76
2696.73 3235.08 2965.91 2,131 8.10 23,086 5,357 87.74 20.36
3235.08 3773.43 3504.25 1,512 5.75 24,598 3,226 93.49 12.26
3773.43 4311.77 4042.60 687 2.61 25,285 1,714 96.10 6.51
4311.77 4850.12 4580.95 397 1.51 25,682 1,027 97.61 3.90
4850.12 5388.47 5119.29 290 1.10 25,972 630 98.71 2.39
5388.47 5926.81 5657.64 221 0.84 26,193 340 99.55 1.29
5926.81 6465.16 6195.99 80 0.30 26,273 119 99.85 0.45
6465.16 7003.51 6734.33 27 0.10 26,300 39 99.95 0.15
7003.51 7541.85 7272.68 9 0.03 26,309 12 99.99 0.05
7541.85 8080.20 7811.03 3 0.01 26,312 3 100.00 0.01
TOTAL 26312 100
Fuente: Datos ANP 2018

3 Análisis Gráfico

3.1 Histogramas de Frecuencia

col_gris_azulado <- "#5D6D7E"
col_ejes <- "#2E4053"
h_base <- hist(Variable, breaks = breaks_table, plot = FALSE)

# GRÁFICO 1: Histograma Absoluto
par(mar = c(8, 5, 4, 2)) 
plot(h_base, 
     main = "Gráfica No.1: Distribución Absoluta (Sondador)",
     xlab = "Profundidad Sondador (m)", ylab = "Frecuencia Absoluta",
     col = col_gris_azulado, border = "white", axes = FALSE,
     ylim = c(0, max(h_base$counts) * 1.1)) 
axis(1, at = round(h_base$breaks, 0), las = 2, cex.axis = 0.7)
axis(2)
grid(nx=NA, ny=NULL, col="#D7DBDD", lty="dotted") 

# GRÁFICO 2: Histograma Global
par(mar = c(8, 5, 4, 2))
plot(h_base, 
     main = "Gráfica N°2: Distribución Global (Sondador)",
     xlab = "Profundidad Sondador (m)", ylab = "Total Pozos",
     col = col_gris_azulado, border = "white", axes = FALSE, 
     ylim = c(0, sum(h_base$counts))) 
axis(1, at = round(h_base$breaks, 0), las = 2, cex.axis = 0.7)
axis(2)
grid(nx=NA, ny=NULL, col="#D7DBDD", lty="dotted")

3.2 Gráficos Porcentuales

h_porc <- h_base
h_porc$counts <- (h_porc$counts / sum(h_porc$counts)) * 100

# GRÁFICO 3: Porcentajes (Local)
par(mar = c(8, 5, 4, 2))
plot(h_porc,
     main = "Gráfica N°3: Distribución Porcentual (Local)",
     xlab = "Profundidad Sondador (m)", ylab = "Porcentaje (%)",
     col = col_gris_azulado, border = "white", axes = FALSE, freq = TRUE,
     ylim = c(0, max(h_porc$counts)*1.2))
axis(1, at = round(h_base$breaks, 0), las = 2, cex.axis = 0.7)
axis(2)
text(x = h_base$mids, y = h_porc$counts, label = paste0(round(h_porc$counts, 1), "%"), pos = 3, cex = 0.6, col = col_ejes)

# GRÁFICO 4: Global Porcentual
par(mar = c(8, 5, 4, 2))
plot(h_porc,
     main = "Gráfica No.4: Distribución Porcentual (Global)",
     xlab = "Profundidad Sondador (m)", ylab = "% del Total", 
     col = col_gris_azulado, border = "white", axes = FALSE, freq = TRUE,
     ylim = c(0, 100))
axis(1, at = round(h_base$breaks, 0), las = 2, cex.axis = 0.7)
text(x = h_base$mids, y = h_porc$counts, label = paste0(round(h_porc$counts, 1), "%"), pos = 3, cex = 0.6, col = col_ejes)
axis(2)

3.3 Diagrama de Caja y Ojivas

# GRÁFICO 5: Boxplot
par(mar = c(8, 4, 3, 2))
boxplot(Variable, horizontal = TRUE, col = col_gris_azulado, 
        main = "Gráfica No.5: Diagrama de Caja (Cota Altimétrica)",
        xlab = "Cota Altimétrica (m)", outline = TRUE, outpch = 19, 
        outcol = "#C0392B"
        ) 

# GRÁFICO 6: Ojivas
par(mar = c(5, 5, 4, 8), xpd = TRUE) 
x_vals <- breaks_table
plot(x_vals, c(0, Ni_asc), type = "o", col = "#2E4053", lwd=2, pch=19, axes=F,
     main = "Gráfica No.6: Ojivas Ascendente y Descendente",
     xlab = "Profundidad Sondador (m)", ylab = "Frecuencia acumulada")
lines(x_vals, c(Ni_desc, 0), type = "o", col = "#C0392B", lwd=2, pch=19)
axis(1, at = round(breaks_table,0), las=2, cex.axis=0.6)
axis(2)
legend("right", legend = c("Asc", "Desc"), col = c("#2E4053", "#C0392B"), lty = 1, pch = 19, inset = c(-0.15, 0), bty="n")
grid()

4 Resumen Estadístico

media_val   <- mean(Variable)
mediana_val <- median(Variable)
sd_val      <- sd(Variable)

status_atipicos <- if(length(boxplot.stats(Variable)$out) > 0) {
  paste0(length(boxplot.stats(Variable)$out), " [", round(min(boxplot.stats(Variable)$out), 2), "; ", round(max(boxplot.stats(Variable)$out), 2), "]")
} else { "0 (Sin atípicos)" }

df_resumen <- data.frame(
  Variable = "Profundidad Sondador (m)",
  Rango = paste0("[", round(min(Variable), 2), "; ", round(max(Variable), 2), "]"),
  Media = media_val,
  Mediana = mediana_val,
  Moda = paste(round(TDF_Sondador$MC[TDF_Sondador$ni == max(TDF_Sondador$ni)], 2), collapse = ", "),
  Varianza = var(Variable),
  Desv_Std = sd_val,
  CV_Porc = (sd_val / abs(media_val)) * 100,
  Asimetria = skewness(Variable, type = 2),
  Curtosis = kurtosis(Variable, type = 2),
  Atipicos = status_atipicos
)

df_resumen %>%
  gt() %>%
  tab_header(title = md("**CONCLUSIONES Y ESTADÍSTICOS**"), subtitle = "Variable: PROFUNDIDADE_SONDADOR_M") %>%
  fmt_number(columns = c(Media, Mediana, Varianza, Desv_Std, CV_Porc, Curtosis), decimals = 2) %>%
  fmt_number(columns = Asimetria, decimals = 4) %>%
  tab_options(column_labels.background.color = "#2E4053") %>%
  tab_style(style = list(cell_text(weight = "bold", color = "white")), locations = cells_column_labels())
CONCLUSIONES Y ESTADÍSTICOS
Variable: PROFUNDIDADE_SONDADOR_M
Variable Rango Media Mediana Moda Varianza Desv_Std CV_Porc Asimetria Curtosis Atipicos
Profundidad Sondador (m) [5; 8080.2] 1,557.01 1,119.00 812.52 1,615,037.78 1,270.84 81.62 1.2423 1.10 586 [4931; 8080.2]

5 Conclusiones

# Lógica de análisis automático
min_txt <- format(min(Variable), scientific = FALSE)
max_txt <- format(max(Variable), scientific = FALSE)
asimetria_val <- skewness(Variable, type = 2)
centro_valor <- format(round(if(abs(asimetria_val) > 0.5) median(Variable) else mean(Variable), 2), scientific = FALSE)
cv_calc <- (sd(Variable) / abs(mean(Variable))) * 100
tipo_homogeneidad <- if(cv_calc > 30) "heterogénea" else "homogénea"
donde_se_concentra <- if(asimetria_val > 0) "parte media baja" else "parte media alta"
juicio_economico <- if(median(Variable) < 3000) "favorable" else "exigente"

cat(paste0(
  "## Análisis Descriptivo y Económico\n\n",
  "La variable **Profundidad del Sondador** fluctúa entre **", min_txt, "** y **", max_txt, "** metros, ",
  "con un centro de distribución en **", centro_valor, "** metros. ",
  "La muestra se comporta como una variable **", tipo_homogeneidad, "** (CV: ", round(cv_calc, 2), "%), ",
  "concentrándose mayoritariamente en la **", donde_se_concentra, "** de la distribución. ",
  "Desde una perspectiva financiera, el comportamiento se considera **", juicio_economico, "** para la operación."
))

5.1 Análisis Descriptivo y Económico

La variable Profundidad del Sondador fluctúa entre 5 y 8080.2 metros, con un centro de distribución en 1119 metros. La muestra se comporta como una variable heterogénea (CV: 81.62%), concentrándose mayoritariamente en la parte media baja de la distribución. Desde una perspectiva financiera, el comportamiento se considera favorable para la operación.