library(readr); library(dplyr); library(gt); library(MASS)
cat("Librerías cargadas correctamente.\n")
## Librerías cargadas correctamente.
ruta_csv <- file.choose()
datos <- read_csv(ruta_csv, show_col_types = FALSE)
cat("Archivo:", basename(ruta_csv), "| Filas:", nrow(datos), "\n")
## Archivo: oil_and_gas_leases_data (2).csv | Filas: 47757
x_raw <- datos %>%
mutate(PROF = suppressWarnings(as.numeric(DEPTH_OF_WELL))) %>%
filter(!is.na(PROF), PROF > 0) %>%
pull(PROF)
n_conteo <- length(x_raw)
k_sturges <- ceiling(1 + 3.322 * log10(n_conteo))
cat("Observaciones válidas:", n_conteo, "\n")
## Observaciones válidas: 47753
cat("Clases (Regla de Sturges):", k_sturges, "\n")
## Clases (Regla de Sturges): 17
cat("Mínimo:", round(min(x_raw), 4), "| Máximo:", round(max(x_raw), 4), "\n")
## Mínimo: 1 | Máximo: 9999
intervalos_cut <- cut(x, breaks=breaks_vec, right=FALSE, include.lowest=TRUE)
freq_abs <- as.integer(table(intervalos_cut))
hi_dec <- freq_abs / n
Ni_asc <- cumsum(freq_abs); Hi_asc <- cumsum(hi_dec)
Ni_desc <- n - c(0, head(Ni_asc,-1)); Hi_desc <- 1 - c(0, head(Hi_asc,-1))
etiq <- paste0("[",format(round(lim_inf,2),big.mark=",")," - ",format(round(lim_sup,2),big.mark=","),")")
etiq[k] <- paste0("[",format(round(lim_inf[k],2),big.mark=",")," - ",format(round(lim_sup[k],2),big.mark=","),"]")
bind_rows(
data.frame(Intervalo=etiq, MC=round(mc,2), ni=freq_abs,
hi_pct=round(hi_dec*100,2), hi_real=round(hi_dec,4),
Ni_a=Ni_asc, Hi_a=round(Hi_asc,4),
Ni_d=Ni_desc, Hi_d=round(Hi_desc,4), stringsAsFactors=FALSE),
data.frame(Intervalo="TOTAL", MC=NA_real_, ni=sum(freq_abs),
hi_pct=round(sum(hi_dec)*100,2), hi_real=round(sum(hi_dec),4),
Ni_a=max(Ni_asc), Hi_a=round(max(Hi_asc),4),
Ni_d=max(Ni_desc), Hi_d=round(max(Hi_desc),4), stringsAsFactors=FALSE)
) %>%
gt() %>%
tab_header(title=md("**Tabla N\u00b01: Distribución de Frecuencias**"),
subtitle=md(paste0("*Profundidad del Pozo, Kansas (n=",format(n,big.mark=","),")*"))) %>%
cols_label(Intervalo=md("**Intervalo**"), MC=md("**MC**"), ni=md("**ni**"),
hi_pct=md("**hi%**"), hi_real=md("**hi**"),
Ni_a=md("**Ni (asc)**"), Hi_a=md("**Hi (asc)**"),
Ni_d=md("**Ni (desc)**"), Hi_d=md("**Hi (desc)**")) %>%
tab_style(style=list(cell_fill(color="#2C2C2C"),cell_text(color="white",weight="bold")),
locations=cells_column_labels()) %>%
tab_style(style=cell_fill(color="#F5F5F5"), locations=cells_body(rows=seq(1,k+1,by=2))) %>%
tab_style(style=list(cell_fill(color="#D6D6D6"),cell_text(weight="bold")),
locations=cells_body(rows=Intervalo=="TOTAL")) %>%
fmt_missing(columns=everything(), missing_text="-") %>%
tab_source_note(source_note=md("*Autor: Fernando Almeida*")) %>%
tab_options(table.width=pct(100), table.font.size=px(13), data_row.padding=px(6))
| Tabla N°1: Distribución de Frecuencias | ||||||||
| Profundidad del Pozo, Kansas (n=47,753) | ||||||||
| Intervalo | MC | ni | hi% | hi | Ni (asc) | Hi (asc) | Ni (desc) | Hi (desc) |
|---|---|---|---|---|---|---|---|---|
| [ 1.0 - 1,000.8) | 500.9 | 4168 | 8.73 | 0.0873 | 4168 | 0.0873 | 47753 | 1.0000 |
| [1,000.8 - 2,000.6) | 1500.7 | 5971 | 12.50 | 0.1250 | 10139 | 0.2123 | 43585 | 0.9127 |
| [2,000.6 - 3,000.4) | 2500.5 | 5420 | 11.35 | 0.1135 | 15559 | 0.3258 | 37614 | 0.7877 |
| [3,000.4 - 4,000.2) | 3500.3 | 13201 | 27.64 | 0.2764 | 28760 | 0.6023 | 32194 | 0.6742 |
| [4,000.2 - 5,000.0) | 4500.1 | 11219 | 23.49 | 0.2349 | 39979 | 0.8372 | 18993 | 0.3977 |
| [5,000.0 - 5,999.8) | 5499.9 | 5126 | 10.73 | 0.1073 | 45105 | 0.9445 | 7774 | 0.1628 |
| [5,999.8 - 6,999.6) | 6499.7 | 1795 | 3.76 | 0.0376 | 46900 | 0.9821 | 2648 | 0.0555 |
| [6,999.6 - 7,999.4) | 7499.5 | 101 | 0.21 | 0.0021 | 47001 | 0.9843 | 853 | 0.0179 |
| [7,999.4 - 8,999.2) | 8499.3 | 157 | 0.33 | 0.0033 | 47158 | 0.9875 | 752 | 0.0157 |
| [8,999.2 - 9,999] | 9499.1 | 595 | 1.25 | 0.0125 | 47753 | 1.0000 | 595 | 0.0125 |
| TOTAL | - | 47753 | 100.00 | 1.0000 | 47753 | 1.0000 | 47753 | 1.0000 |
| Autor: Fernando Almeida | ||||||||
grises <- gray(seq(0.25, 0.80, length.out=k))
h_obj <- hist(x, breaks=breaks_vec, plot=FALSE)
h_obj$density <- hi_dec
par(mar=c(5,6,6,2))
plot(h_obj, col=grises, border="black", freq=FALSE,
main="", xlab="", ylab="", las=1, xaxt="n")
axis(1, at=breaks_vec, labels=format(round(breaks_vec,0),big.mark=","), las=1, cex.axis=0.8)
mtext("Densidad de Probabilidad", side=2, line=4.5, cex=1)
mtext("Profundidad del Pozo (pies)", side=1, line=3.5, cex=1)
mtext("Histograma General - Profundidad del Pozo, Kansas, EE.UU.",
side=3, line=3, cex=0.95, font=2)
El histograma de DEPTH_OF_WELL (profundidad del pozo)
presenta una forma aproximadamente acampanada, centrada entre 3,000 y
5,000 pies, consistente con una variable de tipo continuo con
comportamiento Normal. Se observa un pequeño artefacto
en el extremo superior (una concentración puntual en 9,999 pies) que
corresponde a un tope de registro del dataset, no a un comportamiento
poblacional real; no afecta de forma relevante el ajuste global. Se
conjetura el modelo Normal, contrastándolo también contra Log-Normal y
Exponencial (ambos desplazados al mínimo cuando corresponde).
set.seed(42)
lbl <- c(normal = "Normal", lognormal = "Log-Normal", exponential = "Exponencial")
k_adaptativo <- function(n) {
max(3, min(k, ceiling(1 + 3.322 * log10(n))))
}
calc_pearson_zona <- function(datos, modelo, fit, offset, lim_min, lim_max) {
k_zona <- k_adaptativo(length(datos))
brks <- seq(lim_min, lim_max, length.out = k_zona + 1)
hi_obs <- hist(datos, breaks = brks, plot = FALSE)$counts / length(datos)
mc_z <- (head(brks,-1) + tail(brks,-1)) / 2
if (modelo == "lognormal") {
mc_pos <- mc_z - offset; mc_pos[mc_pos <= 0] <- 1e-9
hi_teo <- dlnorm(mc_pos, meanlog = fit$estimate["meanlog"],
sdlog = fit$estimate["sdlog"]) * diff(brks)
} else if (modelo == "exponential") {
mc_pos <- mc_z - offset; mc_pos[mc_pos <= 0] <- 1e-9
hi_teo <- dexp(mc_pos, rate = fit$estimate["rate"]) * diff(brks)
} else {
hi_teo <- dnorm(mc_z, mean = fit$estimate["mean"], sd = fit$estimate["sd"]) * diff(brks)
}
hi_teo <- hi_teo / sum(hi_teo)
round(cor(hi_obs, hi_teo) * 100, 2)
}
evaluar_modelo <- function(datos, n_samp = 350, lim_min, lim_max) {
set.seed(42)
n_s <- min(n_samp, length(datos))
samp <- sample(datos, size = n_s, replace = FALSE)
offset <- min(datos) - 0.001
d_pos <- datos - offset
s_pos <- samp - offset
resultados <- list()
tryCatch({
f <- fitdistr(datos, "normal")
ks <- ks.test(samp, "pnorm",
mean = f$estimate["mean"], sd = f$estimate["sd"])
resultados[["normal"]] <- list(
fit = f, pval = ks$p.value,
pearson = calc_pearson_zona(datos, "normal", f, 0, lim_min, lim_max),
offset = 0)
}, error = function(e){})
tryCatch({
f <- fitdistr(d_pos, "lognormal")
ks <- ks.test(s_pos, "plnorm",
meanlog = f$estimate["meanlog"], sdlog = f$estimate["sdlog"])
resultados[["lognormal"]] <- list(
fit = f, pval = ks$p.value,
pearson = calc_pearson_zona(datos, "lognormal", f, offset, lim_min, lim_max),
offset = offset)
}, error = function(e){})
tryCatch({
f <- fitdistr(d_pos, "exponential")
ks <- ks.test(s_pos, "pexp", rate = f$estimate["rate"])
resultados[["exponential"]] <- list(
fit = f, pval = ks$p.value,
pearson = calc_pearson_zona(datos, "exponential", f, offset, lim_min, lim_max),
offset = offset)
}, error = function(e){})
mejor <- NULL
mejor_pearson <- -Inf
for (nombre in names(resultados)) {
valor_pearson <- resultados[[nombre]]$pearson
if (!is.na(valor_pearson) && valor_pearson > mejor_pearson) {
mejor_pearson <- valor_pearson
mejor <- nombre
}
}
c(resultados[[mejor]], list(modelo = mejor))
}
validar <- function(datos, res, lim_min, lim_max) {
set.seed(42)
samp <- sample(datos, size = min(50, length(datos)), replace = FALSE)
offset <- res$offset
pearson <- calc_pearson_zona(datos, res$modelo, res$fit, offset, lim_min, lim_max)
if (res$modelo == "lognormal") {
ks_res <- ks.test(samp - offset, "plnorm",
meanlog = res$fit$estimate["meanlog"],
sdlog = res$fit$estimate["sdlog"])
} else if (res$modelo == "exponential") {
ks_res <- ks.test(samp - offset, "pexp", rate = res$fit$estimate["rate"])
} else {
ks_res <- ks.test(samp, "pnorm",
mean = res$fit$estimate["mean"],
sd = res$fit$estimate["sd"])
}
pval_ks <- round(ks_res$p.value, 4)
if (pearson > 70) {
resultado_val <- "APROBADO"
} else {
resultado_val <- "RECHAZADO"
}
list(pearson = pearson, pval = pval_ks, val = resultado_val)
}
r_prof <- evaluar_modelo(x, lim_min = x_min, lim_max = x_max)
v_prof <- validar(x, r_prof, x_min, x_max)
cat("Modelo seleccionado:", lbl[r_prof$modelo], "\n")
## Modelo seleccionado: Normal
cat("Parámetros:\n"); print(round(r_prof$fit$estimate, 6))
## Parámetros:
## mean sd
## 3553.702 1704.593
cat("Pearson R%:", v_prof$pearson, "| KS p-valor:", v_prof$pval, "|", v_prof$val, "\n")
## Pearson R%: 92.23 | KS p-valor: 0.6806 | APROBADO
offset_prof <- r_prof$offset
xs <- seq(x_min, x_max, length.out = 500)
if (r_prof$modelo == "lognormal") {
xs_pos <- xs - offset_prof; xs_pos[xs_pos <= 0] <- 1e-9
ys <- dlnorm(xs_pos, meanlog = r_prof$fit$estimate["meanlog"],
sdlog = r_prof$fit$estimate["sdlog"])
} else if (r_prof$modelo == "exponential") {
xs_pos <- xs - offset_prof; xs_pos[xs_pos <= 0] <- 1e-9
ys <- dexp(xs_pos, rate = r_prof$fit$estimate["rate"])
} else {
ys <- dnorm(xs, mean = r_prof$fit$estimate["mean"], sd = r_prof$fit$estimate["sd"])
}
par(mar=c(5,6,6,2))
plot(h_obj, col=grises, border="black", freq=FALSE,
main="", xlab="", ylab="", las=1, xaxt="n",
ylim=range(c(hi_dec, ys), na.rm=TRUE))
axis(1, at=breaks_vec, labels=format(round(breaks_vec,0),big.mark=","), las=1, cex.axis=0.8)
lines(xs, ys, col="black", lwd=2.5)
mtext("Densidad de Probabilidad", side=2, line=4.5, cex=1)
mtext("Profundidad del Pozo (pies)", side=1, line=3.5, cex=1)
mtext(paste0("Ajuste ", lbl[r_prof$modelo], " - Profundidad del Pozo, Kansas, EE.UU."),
side=3, line=3, cex=0.95, font=2)
legend("topright",
legend = c("Histograma", paste0("Curva ", lbl[r_prof$modelo])),
fill = c("gray55", NA), border = c("black", NA),
lty = c(NA, 1), lwd = c(NA, 2.5), bty = "n", cex = 0.9)
tabla_resumen <- data.frame(
Zona = "Profundidad del Pozo (rango completo)",
Modelo = as.character(lbl[r_prof$modelo]),
Pearson = v_prof$pearson,
KS_p = v_prof$pval,
Validacion = v_prof$val,
stringsAsFactors = FALSE
)
tabla_resumen %>%
gt() %>%
tab_header(
title = md("**Tabla N\u00b02: Resumen de Validación**"),
subtitle = md("*Pearson (R%) y Kolmogorov-Smirnov (p-valor)*")
) %>%
cols_label(Zona=md("**Zona**"), Modelo=md("**Modelo Aplicado**"),
Pearson=md("**Pearson (R %)**"), KS_p=md("**K-S (p-valor)**"),
Validacion=md("**Validación**")) %>%
tab_style(style=list(cell_fill(color="#2C2C2C"),cell_text(color="white",weight="bold")),
locations=cells_column_labels()) %>%
tab_style(style=list(cell_fill(color="#2C2C2C"),cell_text(color="white",weight="bold")),
locations=cells_title(groups="title")) %>%
tab_style(style=cell_text(color="darkgreen",weight="bold"),
locations=cells_body(columns=Validacion, rows=Validacion=="APROBADO")) %>%
tab_style(style=cell_text(color="darkred",weight="bold"),
locations=cells_body(columns=Validacion, rows=Validacion=="RECHAZADO")) %>%
tab_style(style=cell_borders(sides="bottom",color="#E0E0E0",weight=px(1)),
locations=cells_body(rows=everything())) %>%
cols_align(align="center", columns=c(Pearson,KS_p,Validacion)) %>%
cols_align(align="left", columns=c(Zona,Modelo)) %>%
fmt_number(columns=Pearson, decimals=2) %>%
fmt_number(columns=KS_p, decimals=4) %>%
tab_source_note(source_note=md("*Autor: Fernando Almeida*")) %>%
tab_options(table.width=pct(90), table.font.size=px(13),
heading.title.font.size=px(16), heading.subtitle.font.size=px(12),
data_row.padding=px(6),
column_labels.border.top.width=px(2),
column_labels.border.bottom.width=px(2),
table_body.border.bottom.width=px(2),
table.border.top.style="hidden", table.border.bottom.style="hidden")
| Tabla N°2: Resumen de Validación | ||||
| Pearson (R%) y Kolmogorov-Smirnov (p-valor) | ||||
| Zona | Modelo Aplicado | Pearson (R %) | K-S (p-valor) | Validación |
|---|---|---|---|---|
| Profundidad del Pozo (rango completo) | Normal | 92.23 | 0.6806 | APROBADO |
| Autor: Fernando Almeida | ||||
El Intervalo de Confianza representa el puente fundamental entre el modelo empírico observado (Normal) y la estimación poblacional. El TLC garantiza que la distribución de las medias muestrales tenderá a la normalidad debido al volumen masivo de datos (\(n=\) 47,753).
Los postulados de confianza empírica sugieren:
\[P(\bar{x} - E < \mu < \bar{x} + E) \approx 68\%\]
\[P(\bar{x} - 2E < \mu < \bar{x} + 2E) \approx 95\%\]
\[P(\bar{x} - 3E < \mu < \bar{x} + 3E) \approx 99\%\]
Donde el Margen de Error (\(E\)) se define como:
\[E = \frac{\sigma}{\sqrt{n}}\]
media_muestral <- mean(x)
desv_est <- sd(x)
n_total <- length(x)
z_95 <- 1.96
error_est <- desv_est / sqrt(n_total)
margen <- z_95 * error_est
lim_inf_ic <- media_muestral - margen
lim_sup_ic <- media_muestral + margen
data.frame(
Parametro = "Profundidad Promedio del Pozo Kansas (pies)",
Lim_Inferior = round(lim_inf_ic, 2),
Media_Muestral = round(media_muestral, 2),
Lim_Superior = round(lim_sup_ic, 2),
Error_Estandar = paste0("+/- ", round(margen, 2)),
Confianza = "95% (Z=1.96)",
stringsAsFactors = FALSE
) %>%
gt() %>%
tab_header(
title = md("**TABLA N\u00b0 3: ESTIMACIÓN DE LA MEDIA POBLACIONAL**"),
subtitle = md("*Inferencia Estadística para la Variable Profundidad del Pozo*")
) %>%
cols_label(
Parametro = md("**Parámetro**"),
Lim_Inferior = md("**Lim_Inferior**"),
Media_Muestral = md("**Media_Muestral**"),
Lim_Superior = md("**Lim_Superior**"),
Error_Estandar = md("**Error_Estándar**"),
Confianza = md("**Confianza**")
) %>%
tab_style(style = list(cell_fill(color = "#2C2C2C"), cell_text(color = "white", weight = "bold")),
locations = cells_column_labels()) %>%
tab_style(style = list(cell_fill(color = "#2C2C2C"), cell_text(color = "white", weight = "bold")),
locations = cells_title(groups = "title")) %>%
tab_style(style = list(cell_fill(color = "#C8E6C9"), cell_text(weight = "bold")),
locations = cells_body(columns = Media_Muestral)) %>%
tab_style(style = cell_borders(sides = "bottom", color = "#E0E0E0", weight = px(1)),
locations = cells_body(rows = everything())) %>%
cols_align(align = "center", columns = c(Lim_Inferior, Media_Muestral, Lim_Superior, Error_Estandar, Confianza)) %>%
cols_align(align = "left", columns = Parametro) %>%
tab_source_note(source_note = md("*Autor: Fernando Almeida*")) %>%
tab_options(table.width = pct(100), table.font.size = px(13),
heading.title.font.size = px(16), heading.subtitle.font.size = px(12),
data_row.padding = px(6),
column_labels.border.top.width = px(2),
column_labels.border.bottom.width = px(2),
table_body.border.bottom.width = px(2),
table.border.top.style = "hidden", table.border.bottom.style = "hidden")
| TABLA N° 3: ESTIMACIÓN DE LA MEDIA POBLACIONAL | |||||
| Inferencia Estadística para la Variable Profundidad del Pozo | |||||
| Parámetro | Lim_Inferior | Media_Muestral | Lim_Superior | Error_Estándar | Confianza |
|---|---|---|---|---|---|
| Profundidad Promedio del Pozo Kansas (pies) | 3538.41 | 3553.7 | 3568.99 | +/- 15.29 | 95% (Z=1.96) |
| Autor: Fernando Almeida | |||||
Se trabajó con la variable DEPTH_OF_WELL (profundidad
del pozo) sobre su rango completo (1 a 9,999 pies), sin
necesidad de recortar valores atípicos ni dividir en zonas. Se evaluaron
los modelos Normal, Log-Normal y Exponencial, y se seleccionó el de
mayor correlación de Pearson: Normal (media =
3553.7024, sd = 1704.5927). La prueba de Pearson obtuvo
92.23% y el p-valor de Kolmogorov-Smirnov fue
0.6806, por lo que el modelo quedó
APROBADO.
Autor: Fernando Almeida — Análisis Estadístico, Kansas Hydrocarbon Leases Dataset