# ===============================================
# Análisis Estadístico de la Variable Profundidad en Sedimentos Marinos
# Grupo 3
# Tabla con nombres exactos: ni, hi, Ni_asc, Ni_dsc, Hi_asc, Hi_dsc
# ===============================================

setwd("/cloud/project")

library(knitr)

# Lectura y limpieza
datos <- read.csv("Sedimentos Marinos.csv", header = TRUE, sep = ";", dec = ".")
profundidad <- as.numeric(gsub("[^0-9.-]", "", datos$DEPTH_M))
## Warning: NAs introduced by coercion
profundidad <- na.omit(profundidad)

n <- length(profundidad)
k <- ceiling(1 + 3.322 * log10(n))
minimo <- min(profundidad)
maximo <- max(profundidad)
rango <- maximo - minimo
A <- ceiling(rango / k)

# Intervalos
Li <- seq(from = floor(minimo / A) * A, by = A, length.out = k)
Ls <- Li + A
Ls[k] <- maximo + 1e-6
MC <- (Li + Ls) / 2

# Frecuencias
ni <- numeric(k)
for (i in 1:k) {
  if (i == k) {
    ni[i] <- sum(profundidad >= Li[i])
  } else {
    ni[i] <- sum(profundidad >= Li[i] & profundidad < Ls[i])
  }
}

hi <- round(100 * ni / n, 2)
Ni_asc <- cumsum(ni)
Ni_dsc <- rev(cumsum(rev(ni)))
Hi_asc <- round(cumsum(hi), 2)
Hi_dsc <- round(rev(cumsum(rev(hi))), 2)

colores <- gray.colors(k, start = 0.3, end = 0.9)

# Breaks seguros
breaks_hist <- sort(unique(c(Li, Ls, maximo + 1)))

# Etiquetas de intervalos
intervalos <- paste(round(Li, 0), "a", round(Ls - 1, 0))

# === TABLA CON NOMBRES EXACTOS COMO PEDISTE ===
cat("\n=== TABLA DE DISTRIBUCIÓN DE FRECUENCIAS - PROFUNDIDAD (m) ===\n")
## 
## === TABLA DE DISTRIBUCIÓN DE FRECUENCIAS - PROFUNDIDAD (m) ===
TDF <- data.frame(
  Intervalo = intervalos,
  `Marca Clase` = round(MC, 0),
  ni = ni,
  hi = hi,
  Ni_asc = Ni_asc,
  Ni_dsc = Ni_dsc,
  Hi_asc = Hi_asc,
  Hi_dsc = Hi_dsc
)

# Fila de totales
totales <- data.frame(
  Intervalo = "Total",
  `Marca Clase` = "",
  ni = n,
  hi = 100.00,
  Ni_asc = "",
  Ni_dsc = "",
  Hi_asc = "",
  Hi_dsc = ""
)
TDF <- rbind(TDF, totales)

print(kable(TDF, align = "c"))
## 
## 
## |   Intervalo    | Marca.Clase |  ni   |   hi   | Ni_asc | Ni_dsc | Hi_asc | Hi_dsc |
## |:--------------:|:-----------:|:-----:|:------:|:------:|:------:|:------:|:------:|
## | -10170 a -9041 |    -9605    | 1693  | 11.94  |  1693  | 14175  | 11.94  |  100   |
## | -9040 a -7911  |    -8475    |   0   |  0.00  |  1693  | 12482  | 11.94  | 88.06  |
## | -7910 a -6781  |    -7345    |   0   |  0.00  |  1693  | 12482  | 11.94  | 88.06  |
## | -6780 a -5651  |    -6215    |   0   |  0.00  |  1693  | 12482  | 11.94  | 88.06  |
## | -5650 a -4521  |    -5085    |   0   |  0.00  |  1693  | 12482  | 11.94  | 88.06  |
## | -4520 a -3391  |    -3955    |   0   |  0.00  |  1693  | 12482  | 11.94  | 88.06  |
## | -3390 a -2261  |    -2825    |   0   |  0.00  |  1693  | 12482  | 11.94  | 88.06  |
## | -2260 a -1131  |    -1695    |   0   |  0.00  |  1693  | 12482  | 11.94  | 88.06  |
## |   -1130 a -1   |    -565     |   0   |  0.00  |  1693  | 12482  | 11.94  | 88.06  |
## |    0 a 1129    |     565     | 11811 | 83.32  | 13504  | 12482  | 95.26  | 88.06  |
## |  1130 a 2259   |    1695     |  355  |  2.50  | 13859  |  671   | 97.76  |  4.74  |
## |  2260 a 3389   |    2825     |  117  |  0.83  | 13976  |  316   | 98.59  |  2.24  |
## |  3390 a 4519   |    3955     |  154  |  1.09  | 14130  |  199   | 99.68  |  1.41  |
## |  4520 a 5649   |    5085     |  23   |  0.16  | 14153  |   45   | 99.84  |  0.32  |
## |  5650 a 6944   |    6298     |  22   |  0.16  | 14175  |   22   |  100   |  0.16  |
## |     Total      |             | 14175 | 100.00 |        |        |        |        |
# === GRÁFICAS (etiquetas claras) ===

# Gráfica Nº2: Absoluta local
hist(profundidad, breaks = breaks_hist, col = colores, border = "black",
     main = "Gráfica Nº2: Distribución absoluta local de la profundidad en sedimentos marinos",
     xlab = "Profundidad (m)",
     ylab = "Frecuencia absoluta")

# Gráfica Nº3: Absoluta global
hist(profundidad, breaks = breaks_hist, col = colores, border = "black",
     main = "Gráfica Nº3: Distribución absoluta global de la profundidad en sedimentos marinos",
     xlab = "Profundidad (m)",
     ylab = "Frecuencia absoluta",
     ylim = c(0, max(ni) + 10))

# Preparación barras
min_len <- min(length(hi), length(intervalos))
hi_plot <- hi[1:min_len]
intervalos_plot <- intervalos[1:min_len]
colores_plot <- colores[1:min_len]

# Gráfica Nº4: Relativa local
barplot(hi_plot, names.arg = intervalos_plot, col = colores_plot,
        space = 0, las = 2, cex.names = 0.8,
        ylim = c(0, max(hi_plot) + 10),
        main = "Gráfica Nº4: Distribución relativa local de la profundidad en sedimentos marinos",
        xlab = "Intervalos de profundidad (m)",
        ylab = "Porcentaje")

# Gráfica Nº5: Relativa global
barplot(hi_plot, names.arg = intervalos_plot, col = colores_plot,
        space = 0, las = 2, cex.names = 0.8,
        ylim = c(0, 100),
        main = "Gráfica Nº5: Distribución relativa global de la profundidad en sedimentos marinos",
        xlab = "Intervalos de profundidad (m)",
        ylab = "Porcentaje")

# Ojivas
x_asc <- c(Li[1], Ls)
x_desc <- c(Ls, Ls[k] + A)

plot(x_asc, c(0, Ni_asc), type = "o", pch = 16, col = "dodgerblue", lwd = 3,
     main = "Ojiva de frecuencias absolutas acumuladas",
     xlab = "Profundidad (m)",
     ylab = "Frecuencia acumulada absoluta")
lines(x_desc, c(Ni_dsc, 0), type = "o", pch = 17, col = "firebrick", lwd = 3)
legend("topleft", legend = c("Ascendente", "Descendente"),
       col = c("dodgerblue", "firebrick"), pch = c(16, 17), lwd = 3)

plot(x_asc, c(0, Hi_asc), type = "o", pch = 16, col = "dodgerblue", lwd = 3,
     main = "Ojiva de frecuencias relativas acumuladas",
     xlab = "Profundidad (m)",
     ylab = "Frecuencia acumulada relativa (%)",
     ylim = c(0, 105))
lines(x_desc, c(Hi_dsc, 0), type = "o", pch = 17, col = "firebrick", lwd = 3)
legend("bottomright", legend = c("Ascendente", "Descendente"),
       col = c("dodgerblue", "firebrick"), pch = c(16, 17), lwd = 3)

# Boxplot
boxplot(profundidad, horizontal = TRUE, col = "lightblue", border = "darkblue",
        main = "Diagrama de caja y bigotes de la profundidad",
        xlab = "Profundidad (m)")

# Medidas estadísticas
cat("\n=== MEDIDAS ESTADÍSTICAS ===\n")
## 
## === MEDIDAS ESTADÍSTICAS ===
indicadores <- data.frame(
  Media = round(mean(profundidad), 2),
  Mediana = round(median(profundidad), 2),
  `Desviación estándar` = round(sd(profundidad), 2),
  Q1 = round(quantile(profundidad, 0.25), 2),
  Q3 = round(quantile(profundidad, 0.75), 2),
  `Rango intercuartílico` = round(IQR(profundidad), 2)
)
print(kable(indicadores, align = "c"))
## 
## 
## |    |  Media   | Mediana | Desviación.estándar |  Q1  | Q3 | Rango.intercuartílico |
## |:---|:--------:|:-------:|:-------------------:|:----:|:--:|:---------------------:|
## |25% | -1022.34 |   30    |       3364.54       | 9.57 | 67 |         57.44         |
cat("\n¡Análisis completado! Tabla con nombres exactos: ni, hi, Ni_asc, Ni_dsc, Hi_asc, Hi_dsc\n")
## 
## ¡Análisis completado! Tabla con nombres exactos: ni, hi, Ni_asc, Ni_dsc, Hi_asc, Hi_dsc