# CARGA DE DATOS
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
library(knitr)
library(gt)
library(scatterplot3d)
setwd("C:/Users/HP/Documents/PROYECTO ESTADISTICA/RStudio")
datos <- read.csv("tablap.csv", header = TRUE, sep = ";", dec = ",")

# Adaptación de variables
# y = Volumen, x1 = Slope, x2 = Profundidad Vertical
volumen     <- as.numeric(datos$Volume.excavated.soil..slope)
slope       <- as.numeric(datos$Slope)
profundidad <- as.numeric(datos$Vertical.depth.of.well) 

TPV <- data.frame(y = volumen, x1 = slope, x2 = profundidad)
TPV <- na.omit(TPV)

# solo positivos
TPV <- TPV[TPV$y > 0 & TPV$x1 > 0 & TPV$x2 > 0, ]

# filtrar outliers 
filtro_iqr <- function(v){
  Q1 <- quantile(v, 0.25)
  Q3 <- quantile(v, 0.75)
  IQRv <- Q3 - Q1
  li <- Q1 - 1 * IQRv
  ls <- Q3 + 1 * IQRv
  return(v >= li & v <= ls)
}
# TABLA SIN OUTLIERS
TPV <- TPV[filtro_iqr(TPV$y) & filtro_iqr(TPV$x1) & filtro_iqr(TPV$x2), ]

# MOSTRAR SOLO LAS 20 PRIMERAS FILAS DE LA TABLA PROCESADA
head(TPV, 20)
##         y x1   x2
## 8   24829  4 4861
## 11   8340  1 3878
## 12  20965  3 3646
## 15  25959  6 3643
## 22   8813  1 4333
## 26  42407  7 4084
## 28  16781  2 4005
## 42  24628  3 4932
## 43   6794  1 4612
## 51  14097  2 4776
## 53   7325  1 4258
## 60   7192  1 4137
## 69   7184  1 5342
## 72   9144  1 3861
## 78  18157  2 4310
## 80  10659  1 4071
## 91   5328  1 4170
## 96   8627  1 4584
## 98   8181  1 3949
## 101 11496  1 3652
# TRABAJAR CON LA MITAD DE LOS DATOS 
set.seed(456)
TPV <- TPV[sample(1:nrow(TPV), nrow(TPV) / 10), ]

# Extraer las variables
x1 <- TPV$x1 # Variable Independiente
x2 <- TPV$x2 # Variable Independiente 
y  <- TPV$y  # Variable Dependiente

# Configuración de escala para evitar amontonamiento en el eje Z
limite_z <- max(y, na.rm = TRUE)
marcas_z <- seq(0, limite_z, length.out = 5)


# Diagrama de Dispersion (Gráfica N°1)
par(mar = c(5, 6, 4, 2)) 
Cobrereg <- scatterplot3d(x1, x2, y, angle = 225, pch = 16, color = "blue",
                          main = "Gráfica N°1: Diagrama de disperción del Volumen, Slope y Profundidad",
                          xlab = "Slope",
                          ylab = "Profundidad Vertical (ft)",
                          zlab = "Volumen (miles de m3)", # ESCALADO VISUAL
                          y.margin.add = 0.9,
                          las = 1, # Etiquetas horizontales
                          z.ticklabs = format(round(marcas_z / 1000), big.mark = ","))

# Diagrama de dispersión (Gráfica N°2)
Cobrereg <- scatterplot3d(x1, x2, y, angle = 225, pch = 16, color = "blue",
                          main = "Gráfica N°2: Comparacion de la realidad \n con el modelo multivariable lineal",
                          xlab = "Slope",
                          ylab = "Profundidad Vertical (ft)",
                          zlab = "Volumen (miles de m3)",
                          y.margin.add = 0.5,
                          las = 1,
                          z.ticklabs = format(round(marcas_z / 1000), big.mark = ","))


# CÁLCULO DE PARAMETROS
regresion_multiple <- lm(y ~ x1 + x2)
regresion_multiple
## 
## Call:
## lm(formula = y ~ x1 + x2)
## 
## Coefficients:
## (Intercept)           x1           x2  
##   1.160e+04    3.131e+03   -4.948e-02
# Creacion del plano
Cobrereg$plane3d(regresion_multiple, col = "black", lwd = 1)

# Formamos la ecuación
a_val <- round(coef(regresion_multiple)[1], 3)
b_val <- round(coef(regresion_multiple)[2], 3)
c_val <- round(coef(regresion_multiple)[3], 3)

plot(1, type = "n", axes = FALSE, xlab = "", ylab = "") 
text(x = 1, y = 1,
     labels = paste0(" Ecuación Multiple Lineal \n Y = a+bx1+cx2 \n Y = ", 
                     a_val, " + ", b_val, "x1 + ", c_val, "x2"),
     cex = 1.5, col = "blue", font = 6)

# TEST DE PEARSON Y DETERMINACIÓN
# CALCULO DE PEARSON
r2 <- summary(regresion_multiple)$r.squared
r_multiple <- sqrt(r2)

cat("\nTEST DE PEARSON (r*100):\n")
## 
## TEST DE PEARSON (r*100):
print(r_multiple * 100)
## [1] 88.02057
cat("\nCoeficiente de determinación (r2):\n")
## 
## Coeficiente de determinación (r2):
print(r2 * 100)
## [1] 77.4762
# RESTRICCIONES
cat("\nRESTRICCIONES:\n")
## 
## RESTRICCIONES:
cat("La interpretación del modelo se limita estrictamente al rango observado de Slope y Profundidad, evitando extrapolaciones fuera del dominio analizado.")
## La interpretación del modelo se limita estrictamente al rango observado de Slope y Profundidad, evitando extrapolaciones fuera del dominio analizado.
# CÁLCULO DE ESTIMACIONES
x1_test <- 10    # Valor de Slope ejemplo
x2_test <- 8500  # Valor de Profundidad ejemplo

C_Est <- a_val + (b_val * x1_test) + (c_val * x2_test)

plot(1, type = "n", axes = FALSE, xlab = "", ylab = "") 
text(x = 1, y = 1,
     labels = paste0("¿Qué volumen se espera al tener una \npendiente de ", x1_test, " y una profundidad de ", x2_test, "? \n\n R = ", round(C_Est, 3), " m3"),
     cex = 1.5, col = "blue", font = 6)

# CONCLUSION
cat("\n--- CONCLUSION ---\n")
## 
## --- CONCLUSION ---
cat(paste0("Entre el volumen y la combinación de Slope y Profundidad existe una regresión múltiple lineal.\n"))
## Entre el volumen y la combinación de Slope y Profundidad existe una regresión múltiple lineal.
cat(paste0("El volumen está influenciado en un ", round(r2 * 100, 2), "% por la combinación de estas variables.\n"))
## El volumen está influenciado en un 77.48% por la combinación de estas variables.
cat(paste0("Por ejemplo: Para un Slope de ", x1_test, " y una profundidad de ", x2_test, " ft, se espera un volumen de ", round(C_Est, 3), " m3."))
## Por ejemplo: Para un Slope de 10 y una profundidad de 8500 ft, se espera un volumen de 42499.905 m3.