#==============================ENCABEZADO===================================
# TEMA: EI Variables Discreta - A??o de inicio de perforacion
# AUTOR: GRUPO 4
# FECHA: 08-02-2026


library(dplyr)
## 
## 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
#--- PASO 0: CARGA Y PREPARACI??N DE DATOS ---
setwd("C:/Users/HP/Documents/PROYECTO ESTADISTICA/RStudio")
datos <- read.csv("tablap.csv", header = TRUE, dec = ".", sep = ";") 

# Limpieza y creaci??n de la variable A??o
datos$Year <- as.integer(as.numeric(gsub("[^0-9]", "", as.character(datos[,2]))))

# Configuraci??n de D??cadas (1950-2029)
datos$Decada <- cut(datos$Year,
                    breaks = seq(1950, 2030, by = 10),
                    labels = c("1950-1959", "1960-1969", "1970-1979", "1980-1989", 
                               "1990-1999", "2000-2009", "2010-2019", "2020-2029"),
                    right = FALSE)

datos <- datos %>% filter(!is.na(Decada))
Tabla_Gral <- as.data.frame(table(datos$Decada))
colnames(Tabla_Gral) <- c("Decada", "ni")

#===============================================================================
# ANALISIS PARTE A: 1950-1989 (MODELO UNIFORME)
#===============================================================================
cat("\n>>> ANALISIS PARTE A: MODELO UNIFORME <<<\n")
## 
## >>> ANALISIS PARTE A: MODELO UNIFORME <<<
# Paso 1: Justificaci??n (Espacio en blanco para completar)
cat("1. JUSTIFICACI??N: La variable es discreta porque... [COMPLETAR]\n")
## 1. JUSTIFICACI??N: La variable es discreta porque... [COMPLETAR]
# Paso 2: TDF (hi relativa)
df_a <- Tabla_Gral[1:4, ]
tdf_a <- data.frame(No = 1:nrow(df_a), Valor_Real = df_a$Decada, ni = df_a$ni, 
                    hi = (df_a$ni / sum(df_a$ni)))
print(tdf_a)
##   No Valor_Real   ni        hi
## 1  1  1950-1959 1130 0.2189922
## 2  2  1960-1969  873 0.1691860
## 3  3  1970-1979 1416 0.2744186
## 4  4  1980-1989 1741 0.3374031
# Paso 3: Grafica Realidad (hi %)
barplot(tdf_a$hi * 100, names.arg = tdf_a$Valor_Real, col = "red", ylim = c(0, 100),
        main = "Grafica Nro. 1: Distribucion de Inicio de Perforacion (Realidad A)",
        xlab = "Decadas", ylab = "hi (%)", las = 2, cex.names = 0.8)
legend("topright", legend = "Realidad", fill = "red", bty = "n")

# Paso 4: Conjetura y Comparaci??n
cat("4. CONJETURA: Debido a la estabilidad, se asocia con el modelo UNIFORME\n")
## 4. CONJETURA: Debido a la estabilidad, se asocia con el modelo UNIFORME
p_unif_a <- rep(1 / nrow(tdf_a), nrow(tdf_a))

pos_a <- barplot(rbind(tdf_a$hi * 100, p_unif_a * 100), beside = TRUE, col = c("red", "blue"),
                 main = "Grafica Nro. 2: Comparacion Realidad vs Modelo (A)", 
                 xlab = "Decadas", ylab = "Probabilidad (%)", ylim = c(0, 100))
axis(1, at = colMeans(pos_a), labels = tdf_a$Valor_Real, las = 2, cex.axis = 0.8)
legend("topright", legend = c("Realidad", "Modelo"), fill = c("red", "blue"), bty = "n")

# Paso 5: Test (Dispersion y Veredicto)
plot(tdf_a$hi, p_unif_a, xlab = "Observado (hi)", ylab = "Esperado (P)",
     main = "Grafica Nro. 3: Dispersion (A)", pch = 19, col = "blue", ylim = c(0, 1))

x2_a <- sum(((tdf_a$hi - p_unif_a)^2) / p_unif_a)
vc_a <- qchisq(0.999, df = nrow(tdf_a) - 1)

tabla_veredicto_A <- data.frame(
  Prueba = c("Coeficiente de Pearson (r)", "Prueba Chi-Cuadrado (X2)"),
  Valor_Obtenido = c("N/A (Constante)", round(x2_a, 6)),
  Criterio_Referencia = c("r >= 0.70", paste("X2 <", round(vc_a, 2))),
  Resultado = c("APROBADO*", ifelse(x2_a < vc_a, "APROBADO", "REPROBADO"))
)
print(tabla_veredicto_A, row.names = FALSE)
##                      Prueba  Valor_Obtenido Criterio_Referencia Resultado
##  Coeficiente de Pearson (r) N/A (Constante)           r >= 0.70 APROBADO*
##    Prueba Chi-Cuadrado (X2)        0.062912          X2 < 16.27  APROBADO
#===============================================================================
# ANALISIS PARTE B: 1990-2029 (MODELO BINOMIAL)
#===============================================================================
cat("\n>>> ANALISIS PARTE B: MODELO BINOMIAL <<<\n")
## 
## >>> ANALISIS PARTE B: MODELO BINOMIAL <<<
# Paso 1: Justificaci??n (Espacio en blanco)
cat("1. JUSTIFICACI??N: [COMPLETAR]\n")
## 1. JUSTIFICACI??N: [COMPLETAR]
# Paso 2: TDF
df_b <- tail(Tabla_Gral, 4)
tdf_b <- data.frame(No = 1:nrow(df_b), Valor_Real = df_b$Decada, ni = df_b$ni, 
                    hi = (df_b$ni / sum(df_b$ni)))
print(tdf_b)
##   No Valor_Real   ni          hi
## 1  1  1990-1999 1687 0.227942170
## 2  2  2000-2009 5223 0.705715444
## 3  3  2010-2019  477 0.064450750
## 4  4  2020-2029   14 0.001891636
# Paso 3: Grafica Realidad (hi %)
barplot(tdf_b$hi * 100, names.arg = tdf_b$Valor_Real, col = "red", ylim = c(0, 100),
        main = "Grafica Nro. 4: Distribucion de Inicio de Perforacion (Realidad B)",
        xlab = "Decadas", ylab = "hi (%)", las = 2, cex.names = 0.8)
legend("topright", legend = "Realidad", fill = "red", bty = "n")

# Paso 4: Conjetura y Comparaci??n
cat("4. CONJETURA: Por la forma de monta??a, se asocia con el modelo BINOMIAL\n")
## 4. CONJETURA: Por la forma de monta??a, se asocia con el modelo BINOMIAL
xi <- 0:(nrow(tdf_b)-1)
n_b <- nrow(tdf_b) - 1
p_b <- sum(xi * tdf_b$hi) / n_b
prob_bin_b <- dbinom(xi, size = n_b, prob = p_b)

pos_b <- barplot(rbind(tdf_b$hi * 100, prob_bin_b * 100), beside = TRUE, col = c("red", "blue"),
                 main = "Grafica Nro. 5: Comparacion Realidad vs Modelo (B)", 
                 xlab = "Decadas", ylab = "Probabilidad (%)", ylim = c(0, 100))
axis(1, at = colMeans(pos_b), labels = tdf_b$Valor_Real, las = 2, cex.axis = 0.8)
legend("topright", legend = c("Realidad", "Modelo"), fill = c("red", "blue"), bty = "n")

# Paso 5: Test (Pearson y Chi-Cuadrado)
r_b <- cor(tdf_b$hi, prob_bin_b)
plot(tdf_b$hi, prob_bin_b, xlab = "Observado (hi)", ylab = "Esperado (P)",
     main = "Grafica Nro. 6: Dispersion y Regresion (B)", pch = 19, col = "blue")
abline(lm(prob_bin_b ~ tdf_b$hi), col = "red", lwd = 2)
text(x = mean(tdf_b$hi), y = max(prob_bin_b), labels = paste("r =", round(r_b, 4)), col = "red", font = 2)

x2_b <- sum(((tdf_b$hi - prob_bin_b)^2) / pmax(prob_bin_b, 0.0001))
vc_b <- qchisq(0.9999, df = nrow(tdf_b) - 1)

tabla_veredicto_B <- data.frame(
  Prueba = c("Coeficiente de Pearson (r)", "Prueba Chi-Cuadrado (X2)"),
  Valor_Obtenido = c(round(r_b, 4), round(x2_b, 6)),
  Criterio_Referencia = c("r >= 0.70", paste("X2 <", round(vc_b, 2))),
  Resultado = c(ifelse(r_b >= 0.7, "APROBADO", "REPROBADO"),
                ifelse(x2_b < vc_b, "APROBADO", "REPROBADO"))
)
print(tabla_veredicto_B, row.names = FALSE)
##                      Prueba Valor_Obtenido Criterio_Referencia Resultado
##  Coeficiente de Pearson (r)       0.845900           r >= 0.70  APROBADO
##    Prueba Chi-Cuadrado (X2)       0.307558          X2 < 21.11  APROBADO
# Paso 6: Pregunta de Probabilidad
ubicacion <- 2
cat("\n6. PREGUNTA: Probabilidad en la ubicacion", ubicacion, "es:", round(dbinom(ubicacion, n_b, p_b)*100, 2), "%\n")
## 
## 6. PREGUNTA: Probabilidad en la ubicacion 2 es: 16.94 %