# =========================================================
#  REGRESIÓN LINEAL SIMPLE 
# =========================================================

# --- 1. IMPORTAR DATOS ---
setwd("/cloud/project/datos")  
datos <- read.csv("Petroleo_Ontaro.csv", header = TRUE, sep = ";", dec = ".", fill = TRUE)

# --- 2. CONVERTIR VARIABLES NUMÉRICAS ---
datos$TOTAL_DEPTH <- as.numeric(gsub(",", ".", datos$TOTAL_DEPTH))
datos$TRUE_VERTICAL_DEPTH <- as.numeric(gsub(",", ".", datos$TRUE_VERTICAL_DEPTH))

# --- 3. FILTRADO INICIAL ---
datos_filtrados <- subset(datos,
                          !is.na(TOTAL_DEPTH) & 
                            !is.na(TRUE_VERTICAL_DEPTH) &
                            TOTAL_DEPTH > 100 & 
                            TRUE_VERTICAL_DEPTH > 100,
                          select = c(TOTAL_DEPTH, TRUE_VERTICAL_DEPTH))

# --- 4. ELIMINACIÓN DE OUTLIERS  ---
eliminar_outliers <- function(x) {
  Q1 <- quantile(x, 0.25, na.rm = TRUE)
  Q3 <- quantile(x, 0.75, na.rm = TRUE)
  IQR <- Q3 - Q1
  limites <- (x >= (Q1 - 1.5 * IQR)) & (x <= (Q3 + 1.5 * IQR))
  return(limites)
}

sin_outliers <- eliminar_outliers(datos_filtrados$TOTAL_DEPTH) &
  eliminar_outliers(datos_filtrados$TRUE_VERTICAL_DEPTH)

datos_limpios <- datos_filtrados[sin_outliers, ]

# --- 5. MODELO DE REGRESIÓN LINEAL ---
regresionLineal <- lm(TOTAL_DEPTH ~ TRUE_VERTICAL_DEPTH, data = datos_limpios)

# --- 6. RESULTADOS DEL MODELO ---
cat("\n📈 Resumen del modelo de regresión lineal simple:\n")
## 
## 📈 Resumen del modelo de regresión lineal simple:
print(summary(regresionLineal))
## 
## Call:
## lm(formula = TOTAL_DEPTH ~ TRUE_VERTICAL_DEPTH, data = datos_limpios)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -64.33  -0.41  -0.27  -0.18 534.98 
## 
## Coefficients:
##                      Estimate Std. Error  t value Pr(>|t|)    
## (Intercept)         0.0230283  0.1311291    0.176    0.861    
## TRUE_VERTICAL_DEPTH 1.0008801  0.0003339 2997.792   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 9.775 on 22258 degrees of freedom
## Multiple R-squared:  0.9975, Adjusted R-squared:  0.9975 
## F-statistic: 8.987e+06 on 1 and 22258 DF,  p-value: < 2.2e-16
# --- 7. GRÁFICO DE DISPERSIÓN ---
plot(datos_limpios$TRUE_VERTICAL_DEPTH, datos_limpios$TOTAL_DEPTH,
     xlab = "Profundidad Vertical Verdadera (m)",
     ylab = "Profundidad Total (m)",
     main = "Grafica No.1 Regresión Lineal Simple",
     col = "steelblue", pch = 16)
abline(regresionLineal, col = "red", lwd = 2)

# --- 8. CORRELACIÓN Y R² ---
r <- cor(datos_limpios$TRUE_VERTICAL_DEPTH, datos_limpios$TOTAL_DEPTH, use = "complete.obs")
r2 <- r^2 * 100
cat("\nCoeficiente de correlación (r):", round(r, 4), "\n")
## 
## Coeficiente de correlación (r): 0.9988
cat("Coeficiente de determinación (R²):", round(r2, 2), "%\n")
## Coeficiente de determinación (R²): 99.75 %
# Conclusion

conclusion <-"Existe una relación lineal fuerte y positiva entre la Profundidad Vertical Verdadera y la Profundidad Total (R² = 99.75%). El modelo indica que por cada metro que aumenta la profundidad vertical, la profundidad total aumenta. El modelo es confiable para hacer estimaciones dentro del rango analizado."