# UNIVERSIDAD CENTRAL DEL ECUADOR
# FACULTAD DE INGENIERÍA EN MINAS, PETRÓLEOS Y AMBIENTAL 
# TEMA: VARIABLE CONTINUA - REGRESIÓN EXPONENCIAL
# AUTOR: DOMÉNICA YEPEZ

# DIRECTORIO DE TRABAJO 
setwd("C:/Users/HP/OneDrive - Universidad Central del Ecuador/SEMESTRE III/Estadistica/Incendios en Chile/Datos")

# CARGAR LIBRERÍAS
library(readxl)
library(knitr)

# CARGAR DATOS 
datos <- read_excel("iNCENDIOS_FORESTALES_CHILE_DATOS.xlsx")

######################
# RELACIÓN ENTRE VARIABLES 
######################

options(scipen = 999)

# Variables
x <- as.numeric(datos$total_veg)
y <- as.numeric(datos$sup_t_a)
# Filtrar datos válidos
fil <- which(!is.na(x) & !is.na(y) & x > 0 & y > 0 )
x_fil <- x[fil]
y_fil <- y[fil]

# Gráfica de dispersión
plot(x_fil, y_fil,
     main = "Gráfica N°9: Diagrama de dispersión",
     ylab = "Superficie total afectada (ha)",
     xlab = "Superficie total de vegetación (ha)",
     pch = 1, col = "red")

# Aplicar log a y
y_log1 <- log(y_fil)

# Ajustar modelo lineal a log(y) ~ x
regresion_exponencial1  <- lm(y_log1 ~ x_fil)
summary(regresion_exponencial1)
## 
## Call:
## lm(formula = y_log1 ~ x_fil)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -22.1291  -1.6228  -0.0138   1.6333   8.2842 
## 
## Coefficients:
##                Estimate  Std. Error t value            Pr(>|t|)    
## (Intercept) -0.67987549  0.03941445  -17.25 <0.0000000000000002 ***
## x_fil        0.00097066  0.00005332   18.20 <0.0000000000000002 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 2.651 on 4547 degrees of freedom
## Multiple R-squared:  0.06793,    Adjusted R-squared:  0.06773 
## F-statistic: 331.4 on 1 and 4547 DF,  p-value: < 0.00000000000000022
# Agregar curva ajustada al gráfico
curve(exp(coef(regresion_exponencial1)[1] + coef(regresion_exponencial1)[2] * x),
      add = TRUE, col = "blue", lwd = 2)

r <- cor(x_fil, y_log1)
r
## [1] 0.2606377
 # Filtrar para buena correlación (x ≤ 100, y ≤ 1612.12)
filtro <- which(!is.na(x) & !is.na(y) & x > 0 & y > 0 & x <= 100 & y <= 1612.12)
x_filtrado <- x[filtro]
y_filtrado <- y[filtro]
y_log <- log(y_filtrado)

# Graficar dispersión
plot(x_filtrado, y_filtrado,
     main = "GráficaN°9.1: Dispersión para subconjunto optimizado",
     ylab = "Superficie total afectada (ha)",
     xlab = "Superficie total de vegetación (ha)",
     pch = 1, col = "red")

# Ajuste de regresión exponencial
modelo <- lm(y_log ~ x_filtrado)
a <- coef(modelo)[1]
b <- coef(modelo)[2]
summary(modelo)
## 
## Call:
## lm(formula = y_log ~ x_filtrado)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -7.9238 -1.2490  0.3212  1.6307  5.8523 
## 
## Coefficients:
##              Estimate Std. Error t value            Pr(>|t|)    
## (Intercept) -1.286555   0.032242  -39.90 <0.0000000000000002 ***
## x_filtrado   0.122621   0.003003   40.83 <0.0000000000000002 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 2.037 on 4386 degrees of freedom
## Multiple R-squared:  0.2754, Adjusted R-squared:  0.2752 
## F-statistic:  1667 on 1 and 4386 DF,  p-value: < 0.00000000000000022
# Agregar curva exponencial ajustada
curve(exp(a + b * x), add = TRUE, col = "blue", lwd = 2)

# Coeficiente de correlación
r <- cor(x_filtrado, y_log)
cat("Coeficiente de correlación (r):", round(r, 4), "\n")
## Coeficiente de correlación (r): 0.5248
# Estimar valor de y para x = 80
x_nuevo <- 80
y_estimado <- exp(a + b * x_nuevo)
cat("Superficie afectada estimada para 80 ha de vegetación:", round(y_estimado, 2), "ha\n")
## Superficie afectada estimada para 80 ha de vegetación: 5029.75 ha
# Mostrar resultado gráfico con texto
plot(1, type = "n", axes = FALSE, xlab = "", ylab = "") 
text(x = 1, y = 1, 
     labels = paste("Estimación:\n",
                    "¿Qué superficie se afecta cuando la vegetación es 80 ha?\n",
                    paste0("R: ", round(y_estimado, 2), " ha")),
     cex = 1.4, col = "blue", font = 6)

# Restricción: b > 0
if (b > 0) {
  cat("Restricción cumplida: el parámetro b es positivo.\n")
} else {
  cat("Restricción no cumplida: el parámetro b es negativo.\n")
}
## Restricción cumplida: el parámetro b es positivo.
######################
# TABLA DE CONCLUSIÓN
######################

tabla_resumen <- data.frame(
  Variables = "Superficie total de vegetación (x), Superficie afectada (y)",
  Modelo = "Regresión exponencial",
  Ecuación = "y = a * exp(bx)",
  Parámetros = paste("a =", round(exp(a), 4), ", b =", round(b, 7)),
  Dominio = "x ∈ (0 ; 100]"
)

kable(tabla_resumen, align = 'c', caption = "Conclusiones del Modelo Exponencial (subconjunto optimizado)")
Conclusiones del Modelo Exponencial (subconjunto optimizado)
Variables Modelo Ecuación Parámetros Dominio
Superficie total de vegetación (x), Superficie afectada (y) Regresión exponencial y = a * exp(bx) a = 0.2762 , b = 0.122621 x ∈ (0 ; 100]