# UNIVERSIDAD CENTRAL DEL ECUADOR
# Facultad de Ingeniería en Geología, Minas, Petroleos y Ambiental
# Ingeniería Ambiental
# Autor: Domenica Yepez
# Variable : Continua total_otra

# Directorio de trabajo
setwd("C:/Users/HP/OneDrive - Universidad Central del Ecuador/SEMESTRE III/Estadistica/Incendios en Chile/Datos")
# Cargar los datos 
library(readr)
datos <- read_delim("Conaf_Data_Chile_2017.csv", 
                    delim = ";", escape_double = FALSE, trim_ws = TRUE)
## Rows: 5234 Columns: 30
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ";"
## chr  (5): temporada, ambito, nombre_inc, inicio_c, combus_i
## dbl (23): Column1, codreg, codprov, codcom, numero, utm_este, utm_norte, cau...
## num  (2): long, lat
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# Extraer la variable total otra
total_otra <-na.omit(as.numeric(datos$total_otra)) 
# Analizar la variable por el diagrama de caja 
options(scipen = 999)
Caja_total_otra<- boxplot(total_otra, horizontal = T,
                        main = "Gráfica N°: Distribución de Superficie total
                        no forestal afectada en Chile",
                        xlab = " Superficie (ha) ",
                        col =  "#B5EAD7",
                        pch = 1)

#valores de cero total de no forestales
total_otra_cero<-subset(total_otra, total_otra==0)
length(total_otra_cero)
## [1] 4569
#valores mayores de cero total de no forestales
total_otra.1<- subset(total_otra, total_otra>0)
Caja_total_otra.1<- boxplot(total_otra.1, horizontal=T,
                          main = "Gráfica N°: Distribución de Superficie total de
                          no forestal mayor a cero afectada en Chile",
                          xlab = " Superficie (ha)",
                          col =  "#FFDAC1",
                          pch = 1)

length(total_otra.1)
## [1] 665
#se divide los valores mayores de cero en comunes y no comunes 
total_otra.1_comunes<- subset(total_otra.1,total_otra.1 < min(Caja_total_otra.1$out))
caja_total_otra.1_comunes<- boxplot(total_otra.1_comunes, horizontal=T,
                           main = "Gráfica: Diastribución de Superficie total de
                           no forestal comunes afectada en Chile",
                           xlab = "Superficie (ha)",
                           col =  "#D6E0F0",
                           pch = 1)

total_otra.1_outliers<-  subset(total_otra.1,total_otra.1 >= min(Caja_total_otra.1$out) & total_otra.1 < 200000)
caja_total_otra.1_outliers<- boxplot(total_otra.1_outliers, horizontal=T, 
                            main= "Gráfica: Distribución de Superficie total de
                            no forestal no comunes afectada en Chile",
                            xlab= "Superficie (ha)",
                            col= "#FFDAC1",
                            phc= 1)

# Estadística descriptiva para la variable total otra comun
min <- min(total_otra.1_comunes )
max <- max(total_otra.1_comunes )
R <- max-min
K <- floor(1+3.33*log10(length(total_otra.1_comunes )))
A <-  (R/K)
lim_inf <- seq(from=min,to=max-A,by=A)
lim_sup <- seq(from=min+A,to=max+A,by=A)[1:K]
MC <- (lim_inf+lim_sup)/2

ni <- c()
for (i in 1:K) {
  if (i != K) {
    ni[i] <- length(subset(total_otra.1_comunes,
                           total_otra.1_comunes >= lim_inf[i] & total_otra.1_comunes < lim_sup[i]))
  } else {
    ni[i] <- length(subset(total_otra.1_comunes,
                           total_otra.1_comunes >= lim_inf[i] & total_otra.1_comunes <= lim_sup[i]))
  }
}


sum(ni)
## [1] 558
hi <- ni/sum(ni)*100
sum(hi)
## [1] 100
Ni_asc <- cumsum(ni)
Hi_asc <- cumsum(hi)
Ni_desc <- rev(cumsum(rev(ni)))
Hi_desc <- rev(cumsum(rev(hi)))

TDF_total_otra <- data.frame(round(lim_inf,2),
                           round(lim_sup,2),
                           round(MC,2),ni,
                           round(hi,2), 
                           Ni_asc,
                           Ni_desc,
                           round(Hi_asc,2),
                           round(Hi_desc,2))

colnames(TDF_total_otra) <- c("Lim inf","Lim sup","MC","ni","hi(%)",
                            "Ni asc","Hi asc(%)","Ni desc","Hi desc(%)")
totales <- c(lim_inf = "TOTAL", lim_sup = "-", MC = "-", ni = sum(ni), hi = sum(hi),
             Ni_asc = "-", Ni_desc = "-", Hi_asc = "-", Hi_desc = "-")

TDF_total_otra <- rbind(TDF_total_otra, totales)
TDF_total_otra
##    Lim inf Lim sup     MC  ni hi(%) Ni asc Hi asc(%) Ni desc Hi desc(%)
## 1        1    11.7   6.35 348 62.37    348       558   62.37        100
## 2     11.7    22.4  17.05  76 13.62    424       210   75.99      37.63
## 3     22.4    33.1  27.75  47  8.42    471       134   84.41      24.01
## 4     33.1    43.8  38.45  19  3.41    490        87   87.81      15.59
## 5     43.8    54.5  49.15  20  3.58    510        68    91.4      12.19
## 6     54.5    65.2  59.85  12  2.15    522        48   93.55        8.6
## 7     65.2    75.9  70.55   6  1.08    528        36   94.62       6.45
## 8     75.9    86.6  81.25   6  1.08    534        30    95.7       5.38
## 9     86.6    97.3  91.95  13  2.33    547        24   98.03        4.3
## 10    97.3     108 102.65  11  1.97    558        11     100       1.97
## 11   TOTAL       -      - 558   100      -         -       -          -
#simplificar la tabla de distribucion de frecuencia con el histograma

Hist_densidad <- hist(total_otra.1_comunes , main="Gráfica N°:Distribución de superficie total de
                      no forestal afectada en Chile para la TDF",
                      xlab = "Superficie (ha)",
                      ylab= "Cantidad", col ="#CBAACB") 

k.1 <- length(Hist_densidad$breaks)
Li<- Hist_densidad$breaks[1:(length(Hist_densidad$breaks) - 1)]
Ls <- Hist_densidad$breaks[2:length(Hist_densidad$breaks)]
ni.1 <- Hist_densidad$counts
sum(ni.1)
## [1] 558
MC.1<- Hist_densidad$mids
hi.1 <- (ni.1/sum(ni.1))
sum(hi.1)
## [1] 1
Ni_asc.1<- cumsum(ni.1)
Hi_asc.1 <- cumsum(hi.1)
Ni_desc.1 <- rev(cumsum(rev(ni.1)))
Hi_desc.1 <- rev(cumsum(rev(hi.1)))
TDF_total_otra.1 <- data.frame(Li = round(Li, 2),
                             Ls = round(Ls, 2),
                             MC.1 = round(MC.1, 2),
                             ni.1 = ni.1,
                             hi.1 = round(hi.1 * 100, 2),
                             Ni_asc.1 = Ni_asc.1,
                             Hi_asc.1 = round(Hi_asc.1 * 100, 2),
                             Ni_desc.1 = Ni_desc.1,
                             Hi_desc.1 = round(Hi_desc.1 * 100, 2))

colnames(TDF_total_otra.1) <- c("Lim inf","Lim sup","MC","ni","hi(%)",
                              "Ni asc","Hi asc(%)","Ni desc","Hi desc(%)")
totales <- c(Li = "TOTAL", Ls = "-", MC.1 = "-", ni.1 = sum(ni.1), hi.1 = sum(hi.1*100),
             Ni_asc.1= "-", Ni_desc.1 = "-", Hi_asc.1 = "-", Hi_desc.1 = "-")  

TDF_total_otra.1 <- rbind(TDF_total_otra.1, totales)
TDF_total_otra.1
##    Lim inf Lim sup  MC  ni hi(%) Ni asc Hi asc(%) Ni desc Hi desc(%)
## 1        0      10   5 346 62.01    346     62.01     558        100
## 2       10      20  15  76 13.62    422     75.63     212      37.99
## 3       20      30  25  41  7.35    463     82.97     136      24.37
## 4       30      40  35  25  4.48    488     87.46      95      17.03
## 5       40      50  45  21  3.76    509     91.22      70      12.54
## 6       50      60  55  10  1.79    519     93.01      49       8.78
## 7       60      70  65   5   0.9    524     93.91      39       6.99
## 8       70      80  75   8  1.43    532     95.34      34       6.09
## 9       80      90  85   7  1.25    539     96.59      26       4.66
## 10      90     100  95  15  2.69    554     99.28      19       3.41
## 11     100     110 105   4  0.72    558       100       4       0.72
## 12   TOTAL       -   - 558   100      -         -       -          -
#####################  Gráficas ###############################

# Histograma con la rergla de Sturgest###
breaks_sturges <- c(lim_inf, tail(lim_sup, 1))

hist(total_otra.1_comunes, breaks = breaks_sturges, 
     main = "Gráfica N°: Distribución de Superficie total de no forestal
     comunes afectadas en Chile ",
     col = "salmon",
     xlab = "Superficie (ha)",
     ylab = "Cantidad",
     xaxt = "n")

axis(side = 1, at = breaks_sturges, labels = round(breaks_sturges, 1), las = 1, cex.axis = 0.8)

# Histograma de ni que genera Rstudio 
# Local
hist(total_otra.1_comunes,
     main = "Gráfica N°: Distribución de Superficie total de no forestal
     comunes afectadas en Chile",
     col = "skyblue",
     xlab = "Superficie (ha)",
     ylab = "Cantidad")

# Gobal
hist(total_otra.1_comunes,
     main = "Gráfica N°: Distribución de Superficie total de no forestal
     comunes afectadas en Chile",
     col = "salmon",
     xlab = "Superficie (ha)",
     ylab = "Cantidad",
     ylim=c(0,558))

# Histograma de hi que genera Rstudio 
#Local
barplot(hi.1*100,space=0,
        col = "skyblue",
        main ="Gráfica N°: Distribución de Superficie total de no forestal
        comunes afectadas en Chile",
        ylab="Porcentaje (%)",
        xlab="Superficie (ha)",
        names.arg = MC.1)

# Global
barplot(hi.1*100,space=0,
        col = "salmon",
        main ="Gráfica N°: Distribución de Superficie total de no forestal
        comunes afectadas en Chile",
        ylab="Porcentaje (%)",
        xlab="Superficie (ha)",
        ylim = c(0,100), 
        names.arg = MC.1)

# Ojivas Ni_asc Ni_dsc global y local ####
plot(MC.1, Ni_desc.1,
     main = "Gráfica N°: Ojiva acumulada absoluta de Superficie total de no forestal
     comunes afectada en Chile",
     xlab = " Superficie (ha)",
     ylab = "Cantidad",
     col = "salmon",
     type = "o",
     lwd = 3,
     pch = 16,
     ylim = c(0,558))
lines(MC.1, Ni_asc.1,
      col = "blue",
      type = "o",
      pch = 16,
      lwd = 3)

#  Ojivas Hi_asc y Hi_dsc global y local ###

plot(MC.1, Hi_desc.1*100,
     main = "Gráfica N°: Ojiva acumulada relativa de Superficie total de no forestal
     comunes afectada en Chile",
     xlab = " Superficies (ha)",
     ylab = "Porcentaje (%)",
     col = "salmon",
     type = "o",
     lwd = 3,
     pch = 16,
     ylim = c(0,100))
lines(MC.1, Hi_asc.1*100,
      col = "blue",
      type = "o",
      pch = 16,
      lwd = 3)

### Indicadores ###
# Tendencia central
## Media aritmética
x <- mean(total_otra.1_comunes)
x
## [1] 17.27419
## Mediana 
Me <- median(total_otra.1_comunes)
Me
## [1] 6
# Disperción 
## varianza 
V<-var(total_otra.1_comunes)
V
## [1] 568.5728
## Deviación estandar
desv <- sd(total_otra.1_comunes)
desv
## [1] 23.84476
### coeficiente variabilidad ####
CV <- (desv/x)*100
CV
## [1] 138.0369
# FORMA 
## Asimetria
library(e1071)
## Warning: package 'e1071' was built under R version 4.4.3
As <- skewness(total_otra.1_comunes)
As
## [1] 2.065542
# Curtosis 
Ku<- kurtosis(total_otra.1_comunes)
Ku
## [1] 3.735305
# Outliers 
outliers<- Caja_total_otra.1$out
outliers
##   [1]    667    362    362   5121    690   1200   7610    370   7900  75190
##  [11]   2320    250    250    430    280    604    290    590  20791  49705
##  [21]  23164    133   2662   1012   6386    250    168    300    190    174
##  [31]    200   1892   1014    419    300   1426    302    208    165   9600
##  [41] 106739 404983 139064   6939    568   1498    308    200    698   2753
##  [51]    127    384    299    872    122    130    285    350    852    171
##  [61]    189    320    180    333    600   2000  45227   4513    350   1254
##  [71]   2000   1653   2838   8620    287  28528    446   3457  12161   8580
##  [81]    265   3306    710    270    151    670   1357  10849    811    250
##  [91]    437    400   2928    270    173    499    830   1306    270   1440
## [101]    200    230    215    300    200    320    144
# tabla de indicadores de la variable 
tabla_indicadores <- data.frame(
  Variable = "Latitud",
  Rango = paste0("{", round(min(total_otra.1_comunes)), "-", round(max(total_otra.1_comunes)), "}"),
  Media = round(x, 2),
  Mediana = round(Me, 2),
  Moda = "0-10",
  Varianza = round(V, 2),
  Desviacion = round(desv, 2),
  Coeficiente_Variacion = round(CV, 2),
  Asimetria = round(As, 2),
  Curtosis = round(Ku, 2),
  Valores_Atipicos = paste(length(outliers), "entre [", min(outliers), "-", max(outliers), "]")
)

library(knitr)
kable(tabla_indicadores, align = 'c', caption = "Tabla: Conclusiones de la variable Matorral")
Tabla: Conclusiones de la variable Matorral
Variable Rango Media Mediana Moda Varianza Desviacion Coeficiente_Variacion Asimetria Curtosis Valores_Atipicos
Latitud {1-108} 17.27 6 0-10 568.57 23.84 138.04 2.07 3.74 107 entre [ 122 - 404983 ]