# --- IMPORTAR Y PREPROCESAR LOS DATOS ---

# Cargar CSV

datos <- read.csv("C:/Users/y-oss/OneDrive/Escritorio/brasil rstudios/brasil depurada 12.csv", header = TRUE, sep = ";", dec = ",", fill = TRUE)

# Convertir variables numéricas
datos$PROFUNDIDADE_VERTICAL_M <- as.numeric(gsub(",", ".", datos$PROFUNDIDADE_VERTICAL_M))
datos$PROFUNDIDADE_SONDADOR_M <- as.numeric(gsub(",", ".", datos$PROFUNDIDADE_SONDADOR_M))

# --- FILTRADO INICIAL ---

datos_filtrados <- subset(datos, 
                          PROFUNDIDADE_VERTICAL_M > 4000 & 
                            PROFUNDIDADE_SONDADOR_M > 100, 
                          select = c(PROFUNDIDADE_VERTICAL_M, PROFUNDIDADE_SONDADOR_M))

# --- ELIMINAR VALORES ATÍPICOS USANDO IQR ---

# Función para filtrar outliers por IQR
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)
}

# Aplicar filtro a ambas variables
sin_outliers <- eliminar_outliers(datos_filtrados$PROFUNDIDADE_VERTICAL_M) &
  eliminar_outliers(datos_filtrados$PROFUNDIDADE_SONDADOR_M)

datos_limpios <- datos_filtrados[sin_outliers, ]

# --- REGRESIÓN LINEAL ---

# Gráfico de dispersión
plot(datos_limpios$PROFUNDIDADE_SONDADOR_M, datos_limpios$PROFUNDIDADE_VERTICAL_M,
     xlab = "Profundidad Sondador (m)", ylab = "Profundidad Vertical (m)",
     main = "Gráfico N°1: Dispersión sin valores atípicos", col = "steelblue")

# Modelo de regresión
regresionLineal <- lm(PROFUNDIDADE_VERTICAL_M ~ PROFUNDIDADE_SONDADOR_M, data = datos_limpios)

# Resumen del modelo
summary(regresionLineal)
## 
## Call:
## lm(formula = PROFUNDIDADE_VERTICAL_M ~ PROFUNDIDADE_SONDADOR_M, 
##     data = datos_limpios)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -1333.43    23.45    41.94    64.21   106.46 
## 
## Coefficients:
##                          Estimate Std. Error t value Pr(>|t|)    
## (Intercept)              88.40846  103.51339   0.854    0.394    
## PROFUNDIDADE_SONDADOR_M   0.96825    0.01982  48.859   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 188.1 on 185 degrees of freedom
## Multiple R-squared:  0.9281, Adjusted R-squared:  0.9277 
## F-statistic:  2387 on 1 and 185 DF,  p-value: < 2.2e-16
# Línea de regresión
abline(regresionLineal, col = "blue")

# Correlación y R²
r <- cor(datos_limpios$PROFUNDIDADE_SONDADOR_M, datos_limpios$PROFUNDIDADE_VERTICAL_M, use = "complete.obs")
r2 <- r^2 * 100
print(paste("Coeficiente de correlación (r):", round(r, 4)))
## [1] "Coeficiente de correlación (r): 0.9634"
print(paste("Coeficiente de determinación (R²):", round(r2, 2), "%"))
## [1] "Coeficiente de determinación (R²): 92.81 %"
# Predicción con valor específico
x1 <- 2000  # sondador
y_pred <- coef(regresionLineal)[1] + coef(regresionLineal)[2] * x1
print(paste("Si Sondador =", x1, ", la Profundidad Vertical estimada es:", round(y_pred, 2), "m"))
## [1] "Si Sondador = 2000 , la Profundidad Vertical estimada es: 2024.91 m"
# Mostrar modelo
regresionLineal
## 
## Call:
## lm(formula = PROFUNDIDADE_VERTICAL_M ~ PROFUNDIDADE_SONDADOR_M, 
##     data = datos_limpios)
## 
## Coefficients:
##             (Intercept)  PROFUNDIDADE_SONDADOR_M  
##                 88.4085                   0.9683
# Conclusion

conclusion <- "Existe una relación fuerte y positiva entre la Profundidad del Sondador y la Profundidad Vertical. El modelo indica que por cada metro que aumenta la profundidad del sondador, la profundidad vertical se incrementa aproximadamente 0.97 metros. Esta relación es estadísticamente significativa y el modelo puede utilizarse con confianza para realizar estimaciones dentro del rango de los datos analizados."