#### UNIVERSIDAD CENTRAL DEL ECUADOR ######
#### AUTOR: JHONNY JOSÉ CATUCUAMBA CALCAN ####
#### CARRERA: INGENIERÍA AMBIENTAL ####
### VARIABLES:TOTAL_OTRA, SUP_T_A, TOTAL_VEG ####
### MODELO DE REGRESIÓN MÚLTIPLE LINEAL #####
setwd("/cloud/project")
datos <-  read.csv("Conaf_Data_Chile_2017.csv")

library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
###################### ESTADÍSTICA Multivariable ###############################
plot(1, type = "n", axes = FALSE, xlab = "", ylab = "") # Crear un gráfico vacío
text(x = 1, y = 1,
     labels = "ESTADÍSTICA MULTIVARIABLE",
     cex = 2, # Tamaño del texto (ajustable)
     col = "blue", # Color del texto
     font =6) #tipo

sup_total <- datos$sup_t_a
otraveg_total <- datos$total_otra
veg_total <- datos$total_veg

# 1. Plantear el modelo cuya ecuacion es:
#  y= B0 + B1x1 + B2x2
plot(1, type = "n", axes = FALSE, xlab = "", ylab = "") # Crear un gráfico vacío
text(x = 1, y = 1,
     labels = "Regresión multiple modelo lineal",
     cex = 2, # Tamaño del texto (ajustable)
     col = "blue", # Color del texto
     font =6) #tipo

y <- sup_total
x1 <- otraveg_total
x2 <- veg_total

# 2. Anlizar la correlacion 

library(scatterplot3d)

Grafico <- scatterplot3d(x1, x2, y,
                         main = "Gráfica Nº 10.1: Modelo de regresión múltiple 
                         lineal 3D ",
                         pch = 19,
                         angle = 70,
                         color = 4,
                         ylab = "Vegetación Total",
                         xlab = "Otras Superficies Afectadas",
                         zlab = "Superficie Total Afectada"
)

Tmaxreg <- scatterplot3d(x1, x2, y,
                         main = "Gráfica Nº 10.2: Modelo de regresión múltiple 
                         lineal 3D con plano de regresión",
                         pch = 19,
                         angle = 70,
                         color = 4,
                         ylab = "Vegetación Total",
                         xlab = "Otras Superficies Afectadas",
                         zlab = "Superficie Total Afectada"
)
modelo <- lm(y ~ x1 + x2)
summary(modelo)
## 
## Call:
## lm(formula = y ~ x1 + x2)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -20073     53     56     56  38188 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept) -56.42243   12.25086  -4.606 4.21e-06 ***
## x1           -1.27781    0.13011  -9.821  < 2e-16 ***
## x2            3.53927    0.02735 129.425  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 883.9 on 5231 degrees of freedom
## Multiple R-squared:  0.871,  Adjusted R-squared:  0.8709 
## F-statistic: 1.765e+04 on 2 and 5231 DF,  p-value: < 2.2e-16
b0 <- coef(modelo)[1]
b1 <- coef(modelo)[2]
b2 <- coef(modelo)[3]
Tmaxreg$plane3d(modelo, main = "Gráfica Nº 10.2: Modelo de regresión múltiple 
                lineal 3D con plano de regresión")

b0
## (Intercept) 
##   -56.42243
b1
##        x1 
## -1.277806
b2
##       x2 
## 3.539273
#Formamos la ecuación
plot(1, type = "n", axes = FALSE, xlab = "", ylab = "")  # Crear un gráfico vacío
text(x = 1, y = 1, 
     labels = " Ecuación multiple \n Y= a + bx1 + cx2 
     Y = - 113 - 1.28x1 + 3.54x2",
     cex = 2,  # Tamaño del texto (ajustable)
     col = "blue",  # Color del texto
     font =6) #tipo

# Conjetura: Es un plano

# REsumen de regresion
summary(modelo)
## 
## Call:
## lm(formula = y ~ x1 + x2)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -20073     53     56     56  38188 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept) -56.42243   12.25086  -4.606 4.21e-06 ***
## x1           -1.27781    0.13011  -9.821  < 2e-16 ***
## x2            3.53927    0.02735 129.425  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 883.9 on 5231 degrees of freedom
## Multiple R-squared:  0.871,  Adjusted R-squared:  0.8709 
## F-statistic: 1.765e+04 on 2 and 5231 DF,  p-value: < 2.2e-16
# Test de Pearson
r <- cor(y,x1+x2)
print(paste("Correlación de Pearson: ", round(r, 4)))
## [1] "Correlación de Pearson:  0.9199"
# Coeficinte de determinación
r2 <- (r^2) * 100
print(paste("Coeficinte de determinación: ", round(r2, 2), "%"))
## [1] "Coeficinte de determinación:  84.62 %"
# Restricciones :
# y, x1 , x2 >= 0

# Estimaciones

CE_50_100 <- -113 - (1.28)*50 + (3.54)*100
CE_50_100
## [1] 177
plot(1, type = "n", axes = FALSE, xlab = "", ylab = "") # Crear un gráfico vacío
text(x = 1, y = 1, 
     labels = "¿Que cantidad de Superficie total afectada 
     se espera cuando se tenga 
     50(ha) otra superficie  y 
     100(ha) vegetación total?
     \n R= 177 (ha) ",
     cex = 1.8,  # Tamaño del texto (ajustable)
     col = "blue",  # Color del texto
     font = 6)

# CONCLUSIONES
plot(1, type = "n", axes = FALSE, xlab = "", ylab = "") # Crear un gráfico vacío
text(x = 1, y = 1, 
     labels = "CONCLUSIONES",
     cex = 2,  # Tamaño del texto (ajustable)
     col = "blue",  # Color del texto
     font = 6)

library(knitr)
Tabla_resumen <- data.frame(Variables = c("x1", "x2","y"),
                            Com = c("Regresión múltiple lineal ", "",""),
                            Modelo = c("Otraveg_total (ha) ", "veg_total (ha)","sup_total (ha)"),
                            Restricciones = c("x1 >= 0 ","x2 >= 0","y >= 0"),
                            Coeficiente_pearson = c("0.92 ", "",""),
                            Coeficiente_determinacion = c("84.62 % ","15.38 % ",""),
                            Ecuacion = c("Y = - 113 - 1.28x1 + 3.54x2", "",""))
colnames(Tabla_resumen) <- c("Variables ", "Modelo ","Nombres ", "Restricciones",
                             "Coef. Pearson" , "Coef. Determinación", "Ecuación")

kable(Tabla_resumen, align = 'c', caption = "Resumen del Modelo Múltiple")
Resumen del Modelo Múltiple
Variables Modelo Nombres Restricciones Coef. Pearson Coef. Determinación Ecuación
x1 Regresión múltiple lineal Otraveg_total (ha) x1 >= 0 0.92 84.62 % Y = - 113 - 1.28x1 + 3.54x2
x2 veg_total (ha) x2 >= 0 15.38 %
y sup_total (ha) y >= 0
###### Entre el total veg, la superficie total y Otraveg total de los incendios de Chile en 2017 existe una  
###### relación de Regresión múltiple lineal representada por Y = - 113 - 1.28x1 + 3.54x2 siendo X el total veg en (ha) 
##### Y la superficie total (ha) donde la superficie total es influenciada en un  84.62 % " y el "15.38 % se debe a otras causas
##### y aprueban el test de pearson con un 94% y con restricciones " x >= 4000  (ha)","y > 0 (ha)") 
##### "x1 >= 0 ","x2 >= 0","y >= 0"