0. Carga de librerías

if (!requireNamespace("gt", quietly = TRUE)) {
  install.packages("gt")
}
library(gt)

1. Carga de datos y selección de la variable

# Si sabes la ruta exacta del archivo, escríbela aquí (ej. "C:/Users/TuUsuario/Downloads/database.csv")
ruta_manual <- ""

home_dir <- normalizePath("~", winslash = "/", mustWork = FALSE)
user_profile <- Sys.getenv("USERPROFILE")
if (nzchar(user_profile)) {
  user_profile <- normalizePath(user_profile, winslash = "/", mustWork = FALSE)
}

carpetas_candidatas <- unique(c(
  ".",
  "..",
  home_dir,
  file.path(home_dir, "Downloads"),
  file.path(home_dir, "Downloads", "dataset"),
  file.path(home_dir, "Desktop"),
  file.path(home_dir, "Documents"),
  if (nzchar(user_profile)) c(
    user_profile,
    file.path(user_profile, "Downloads"),
    file.path(user_profile, "Downloads", "dataset"),
    file.path(user_profile, "Desktop"),
    file.path(user_profile, "Documents")
  ) else character(0),
  "C:/Users/USER/Downloads/dataset",
  "C:/Users/USER/Downloads",
  "C:/Users/Anthony - Personal/Downloads",
  "C:/Users/Anthony - Personal/Downloads/dataset"
))
carpetas_existentes <- carpetas_candidatas[dir.exists(carpetas_candidatas)]

archivo <- NULL

if (nzchar(trimws(ruta_manual))) {
  if (!file.exists(ruta_manual)) {
    stop("La 'ruta_manual' especificada no existe: ", ruta_manual)
  }
  archivo <- ruta_manual
}

if (is.null(archivo) && length(carpetas_existentes) > 0) {
  rutas_exactas <- c(
    file.path(carpetas_existentes, "database.csv"),
    file.path(carpetas_existentes, "database.xlsx"),
    file.path(carpetas_existentes, "database.xls"),
    file.path(carpetas_existentes, "database.zip"),
    file.path(carpetas_existentes, "database")
  )
  coincidencias <- rutas_exactas[file.exists(rutas_exactas)]

  if (length(coincidencias) == 0) {
    hallazgos <- unlist(lapply(carpetas_existentes, function(carp) {
      list.files(
        carp,
        pattern = "(database|glacier).*\\.(csv|xlsx|xls|zip)$\vert{}^database$",
        ignore.case = TRUE,
        full.names = TRUE,
        recursive = TRUE
      )
    }))
    hallazgos <- hallazgos[file.exists(hallazgos) & !dir.exists(hallazgos)]
    if (length(hallazgos) > 0) {
      coincidencias <- hallazgos
    }
  }

  if (length(coincidencias) > 0) {
    archivo <- coincidencias[1]
  }
}

if (is.null(archivo)) {
  if (interactive()) {
    message("Selecciona tu archivo 'database' en la ventana...")
    archivo <- file.choose()
  } else {
    carpetas_inspeccion <- unique(c(
      ".",
      file.path(home_dir, "Downloads"),
      if (nzchar(user_profile)) file.path(user_profile, "Downloads") else character(0),
      "C:/Users/Anthony - Personal/Downloads"
    ))
    carpetas_inspeccion <- carpetas_inspeccion[dir.exists(carpetas_inspeccion)]
    archivos_cercanos <- unique(unlist(lapply(carpetas_inspeccion, function(carp) {
      list.files(
        carp,
        pattern = "\\.(csv|xlsx|xls|zip)$",
        ignore.case = TRUE,
        full.names = TRUE
      )
    })))
    stop(
      "No se encontró el archivo 'database' en las rutas esperadas.\n",
      "Carpeta actual del .Rmd: ", normalizePath(".", winslash = "/", mustWork = FALSE), "\n",
      "Carpetas revisadas: ", paste(carpetas_existentes, collapse = " | "), "\n",
      "Archivos de datos encontrados cerca: ",
      if (length(archivos_cercanos) > 0) paste(archivos_cercanos, collapse = ", ") else "ninguno"
    )
  }
}

message("Archivo cargado: ", normalizePath(archivo, winslash = "/", mustWork = FALSE))

if (grepl("\\.zip$", archivo, ignore.case = TRUE)) {
  dir_temp <- tempfile("glaciares_")
  unzip(archivo, exdir = dir_temp)
  csvs <- list.files(dir_temp, pattern = "\\.csv$", full.names = TRUE, recursive = TRUE)
  if (length(csvs) == 0) {
    stop("El archivo .zip no contiene ningún .csv en su interior.")
  }
  idx_db <- grep("database\\.csv$", csvs, ignore.case = TRUE)
  archivo <- if (length(idx_db) > 0) csvs[idx_db[1]] else csvs[1]
}

es_excel <- grepl("\\.(xlsx|xls)$", archivo, ignore.case = TRUE)
if (!es_excel && file.exists(archivo)) {
  cabecera <- tryCatch(readBin(archivo, "raw", n = 2), error = function(e) raw(0))
  if (length(cabecera) == 2 && identical(cabecera, as.raw(c(0x50, 0x4b)))) {
    es_excel <- TRUE
  }
}

if (es_excel) {
  if (!requireNamespace("readxl", quietly = TRUE)) {
    install.packages("readxl")
  }
  datos <- as.data.frame(readxl::read_excel(archivo), stringsAsFactors = FALSE)
  names(datos) <- make.names(names(datos), unique = TRUE)
} else {
  datos <- read.csv(archivo, stringsAsFactors = FALSE, check.names = TRUE)
}

# 2. Buscar columna de Longitud Media con valores numéricos finitos
candidatas <- names(datos)[grepl("(mean.*length|length.*mean|longitud.*media|media.*longitud|length|long)", names(datos), ignore.case = TRUE)]
if (length(candidatas) == 0) {
  candidatas <- names(datos)
}

# Priorizar coincidencias de 'mean' + 'length'
orden_prioridad <- order(!grepl("(mean.*length|length.*mean|longitud.*media|media.*longitud)", candidatas, ignore.case = TRUE))
candidatas <- candidatas[orden_prioridad]

col_elegida <- NULL
LONG_MED <- numeric(0)

for (col_actual in candidatas) {
  texto_limpio <- gsub(",", ".", trimws(as.character(datos[[col_actual]])))
  num_directo <- suppressWarnings(as.numeric(texto_limpio))
  if (all(!is.finite(num_directo))) {
    extraido <- sub("^.*?(-?[0-9]+(\\.[0-9]+)?).*$", "\\1", texto_limpio)
    extraido[!grepl("^-?[0-9]+(\\.[0-9]+)?$", extraido)] <- NA
    num_directo <- suppressWarnings(as.numeric(extraido))
  }
  validos <- num_directo[is.finite(num_directo)]
  if (length(validos) > 0) {
    col_elegida <- col_actual
    LONG_MED <- validos
    break
  }
}

if (length(LONG_MED) == 0) {
  print(names(datos))
  stop("Ninguna columna relacionada con Longitud Media contiene valores numéricos finitos. Revisa los nombres de columnas impresos arriba.")
}

message("Usando columna: ", col_elegida, " (n válidos = ", length(LONG_MED), ")")

2. Tabla de distribución de frecuencias

# 3. Definir límites e intervalos (9 intervalos de amplitud constante)
min_val <- min(LONG_MED)
max_val <- max(LONG_MED)

if (min_val == max_val) {
  limites <- seq(min_val - 0.5, max_val + 0.5, length.out = 10)
} else {
  limites <- pretty(c(min_val, max_val), n = 9)
  if (length(limites) < 2) {
    limites <- seq(floor(min_val), ceiling(max_val), length.out = 10)
  }
}

cortes <- cut(LONG_MED, breaks = limites, right = FALSE, include.lowest = TRUE)
n_inter <- length(limites) - 1

etiquetas_int <- vapply(seq_len(n_inter), function(k) {
  cierre <- if (k < n_inter) ")" else "]"
  paste0("[", limites[k], " - ", limites[k + 1], cierre)
}, character(1))

ni_vec <- as.numeric(table(cortes))
n_total <- sum(ni_vec)
hi_vec <- round((ni_vec / n_total) * 100, 2)
mc_vec <- (limites[-length(limites)] + limites[-1]) / 2

# 4. Construir tabla de frecuencias (Tabla Nro. 22)
TDF_LONG_MED <- data.frame(
  Intervalo = etiquetas_int,
  MC = as.character(round(mc_vec, 2)),
  ni = as.character(ni_vec),
  hi = sprintf("%.2f", hi_vec),
  `Ni ↑` = as.character(cumsum(ni_vec)),
  `Ni ↓` = as.character(rev(cumsum(rev(ni_vec)))),
  `Hi ↑` = as.character(round(cumsum(hi_vec), 2)),
  `Hi ↓` = as.character(round(rev(cumsum(rev(hi_vec))), 2)),
  stringsAsFactors = FALSE,
  check.names = FALSE
)

fila_totales <- data.frame(
  Intervalo = "Totales",
  MC = "-",
  ni = as.character(n_total),
  hi = "100.00",
  `Ni ↑` = "-",
  `Ni ↓` = "-",
  `Hi ↑` = "-",
  `Hi ↓` = "-",
  stringsAsFactors = FALSE,
  check.names = FALSE
)

TDF_LONG_MED_tabla <- rbind(TDF_LONG_MED, fila_totales)

tabla_freq_gt <- gt(TDF_LONG_MED_tabla)
tabla_freq_gt <- cols_align(tabla_freq_gt, align = "left", columns = "Intervalo")
tabla_freq_gt <- cols_align(tabla_freq_gt, align = "right", columns = c("MC", "ni", "hi", "Ni ↑", "Ni ↓", "Hi ↑", "Hi ↓"))
tabla_freq_gt <- tab_header(
  tabla_freq_gt,
  title = "Tabla Nro. 22",
  subtitle = "Distribución de frecuencia de la variable Longitud Media agrupada por intervalos, estudio de los glaciares del mundo"
)
tabla_freq_gt <- tab_source_note(
  tabla_freq_gt,
  source_note = md("Grupo: 1 <br> Fuente: [https://www.kaggle.com/datasets/nsidcorg/glacier-inventory](https://www.kaggle.com/datasets/nsidcorg/glacier-inventory)")
)
tabla_freq_gt <- tab_options(
  tabla_freq_gt,
  table.border.top.style = "solid", table.border.top.color = "black", table.border.top.width = px(1),
  table.border.bottom.style = "solid", table.border.bottom.color = "black", table.border.bottom.width = px(1),
  column_labels.border.top.style = "solid", column_labels.border.top.color = "black", column_labels.border.top.width = px(1),
  column_labels.border.bottom.style = "solid", column_labels.border.bottom.color = "black", column_labels.border.bottom.width = px(1),
  table_body.hlines.style = "solid", table_body.hlines.color = "gray70", table_body.hlines.width = px(1),
  table_body.vlines.style = "solid", table_body.vlines.color = "gray70", table_body.vlines.width = px(1),
  row.striping.include_table_body = FALSE
)
tabla_freq_gt
Tabla Nro. 22
Distribución de frecuencia de la variable Longitud Media agrupada por intervalos, estudio de los glaciares del mundo
Intervalo MC ni hi Ni ↑ Ni ↓ Hi ↑ Hi ↓
[-200 - -150) -175 431 0.32 431 132890 0.32 99.98
[-150 - -100) -125 15656 11.78 16087 132459 12.1 99.66
[-100 - -50) -75 17384 13.08 33471 116803 25.18 87.88
[-50 - 0) -25 2011 1.51 35482 99419 26.69 74.8
[0 - 50) 25 11828 8.90 47310 97408 35.59 73.29
[50 - 100) 75 79528 59.84 126838 85580 95.43 64.39
[100 - 150) 125 1479 1.11 128317 6052 96.54 4.55
[150 - 200] 175 4573 3.44 132890 4573 99.98 3.44
Totales - 132890 100.00 - - - -
Grupo: 1
Fuente: https://www.kaggle.com/datasets/nsidcorg/glacier-inventory

3. Gráficos de distribución de frecuencias

Gráfico 1: Histograma

par(mar = c(6, 6.5, 4, 2))
hist(LONG_MED, breaks = limites, col = "steelblue", border = "white",
     main = "Gráfico Nro. 1: Longitud Media por intervalos de clase, en el estudio de los glaciares del mundo",
     xlab = "", ylab = "", ylim = c(0, n_total), las = 1, xaxt = "n")
axis(1, at = limites, las = 2, cex.axis = 0.8)
title(xlab = "Longitud Media (km)", line = 4.5)
title(ylab = "Cantidad", line = 4.5)

Gráfico 2: Histograma

par(mar = c(6, 6.5, 4, 2))
hist(LONG_MED, breaks = limites, col = "steelblue", border = "white",
     main = "Gráfico Nro. 2: Longitud Media por intervalos de clase, en el estudio de los glaciares del mundo",
     xlab = "", ylab = "", ylim = c(0, max(c(ni_vec, 1)) * 1.15), las = 1, xaxt = "n")
axis(1, at = limites, las = 2, cex.axis = 0.8)
title(xlab = "Longitud Media (km)", line = 4.5)
title(ylab = "Cantidad", line = 4.5)

Gráfico 3: Distribución porcentual

par(mar = c(7, 6.5, 4, 2))
grafico_hi_global <- barplot(hi_vec, names.arg = etiquetas_int, space = 0, col = "darkseagreen3",
                             main = "Gráfico Nro. 3: Longitud Media por intervalos de clase, en el estudio de los glaciares del mundo",
                             xlab = "", ylim = c(0, 100), las = 2, cex.names = 0.75, cex.axis = 0.85)
title(xlab = "Intervalos de Longitud Media (km)", line = 5.5)
title(ylab = "Porcentaje (%)", line = 4.5)
text(x = grafico_hi_global, y = hi_vec, labels = paste0(hi_vec, "%"), pos = 3, cex = 0.75, col = "black")

Gráfico 4: Distribución porcentual

par(mar = c(7, 6.5, 4, 2))
grafico_hi_local <- barplot(hi_vec, names.arg = etiquetas_int, space = 0, col = "darkseagreen3",
                            main = "Gráfico Nro. 4: Longitud Media por intervalos de clase, en el estudio de los glaciares del mundo",
                            xlab = "", ylim = c(0, max(c(hi_vec, 1)) * 1.15), las = 2, cex.names = 0.75, cex.axis = 0.85)
title(xlab = "Intervalos de Longitud Media (km)", line = 5.5)
title(ylab = "Porcentaje (%)", line = 4.5)
text(x = grafico_hi_local, y = hi_vec, labels = paste0(hi_vec, "%"), pos = 3, cex = 0.75, col = "black")

Gráfico 5: Ojivas

par(mar = c(5, 6.5, 4, 2))
Ni_asc <- cumsum(ni_vec)
Ni_desc <- rev(cumsum(rev(ni_vec)))
plot(mc_vec, Ni_asc, type = "o", pch = 16, col = "steelblue", lwd = 2,
     main = "Gráfico Nro. 5: Ojiva de Longitud Media, en el estudio de los glaciares del mundo",
     xlab = "Marca de Clase - Longitud Media (km)", ylab = "", ylim = c(0, n_total), las = 1)
lines(mc_vec, Ni_desc, type = "o", pch = 17, col = "tomato", lwd = 2)
title(ylab = "Frecuencia Acumulada (Ni)", line = 4.8)
legend("left", legend = c("Ni ↑", "Ni ↓"), col = c("steelblue", "tomato"), pch = c(16, 17), lwd = 2, bty = "n")

Gráfico 6: Diagrama de caja

par(mar = c(5, 5, 4, 2))
boxplot(LONG_MED, horizontal = TRUE, col = "lightskyblue", border = "navy",
        main = "Gráfico Nro. 6: Diagrama de Caja de Longitud Media, en el estudio de los glaciares del mundo",
        xlab = "Longitud Media (km)", las = 1)

4. Indicadores Estadísticos

# 6. Indicadores estadísticos (Tabla Nro. 23)
n_lm       <- length(LONG_MED)
min_lm     <- round(min(LONG_MED), 2)
max_lm     <- round(max(LONG_MED), 2)
media      <- round(mean(LONG_MED), 2)
mediana    <- round(median(LONG_MED), 2)
moda_aprox <- round(mc_vec[which.max(ni_vec)], 2)
sd_lm      <- if (n_lm > 1) round(sd(LONG_MED), 2) else 0
var_lm     <- if (n_lm > 1) round(var(LONG_MED), 2) else 0
cv_lm      <- if (!is.na(media) && media != 0) round((sd_lm / abs(media)) * 100, 2) else NA
q1         <- round(quantile(LONG_MED, 0.25), 2)
q3         <- round(quantile(LONG_MED, 0.75), 2)
riq        <- round(IQR(LONG_MED), 2)
asimetria  <- if (n_lm > 2 && sd_lm > 0) round(sum((LONG_MED - mean(LONG_MED))^3) / (n_lm * sd(LONG_MED)^3), 2) else NA
curtosis   <- if (n_lm > 3 && sd_lm > 0) round(sum((LONG_MED - mean(LONG_MED))^4) / (n_lm * sd(LONG_MED)^4) - 3, 2) else NA

indicadores_long_med <- data.frame(
  Indicador = c(
    "Mínimo", "Máximo", "Media Aritmética", "Mediana", "Moda (Marca de clase)",
    "Desviación Estándar", "Varianza", "Coeficiente de Variación (%)",
    "Cuartil 1 (Q1)", "Cuartil 3 (Q3)", "Rango Intercuartílico (RIC)",
    "Coeficiente de Asimetría", "Curtosis"
  ),
  Valor = as.character(c(
    min_lm, max_lm, media, mediana, moda_aprox,
    sd_lm, var_lm, cv_lm,
    q1, q3, riq,
    asimetria, curtosis
  )),
  stringsAsFactors = FALSE
)

tabla_ind_gt <- gt(indicadores_long_med)
tabla_ind_gt <- cols_align(tabla_ind_gt, align = "left", columns = "Indicador")
tabla_ind_gt <- cols_align(tabla_ind_gt, align = "right", columns = "Valor")
tabla_ind_gt <- tab_header(
  tabla_ind_gt,
  title = "Tabla Nro. 23",
  subtitle = "Indicadores estadísticos descriptivos de la variable Longitud Media para el estudio de los glaciares del mundo"
)
tabla_ind_gt <- tab_source_note(
  tabla_ind_gt,
  source_note = md("Grupo: 1 <br> Fuente: [https://www.kaggle.com/datasets/nsidcorg/glacier-inventory](https://www.kaggle.com/datasets/nsidcorg/glacier-inventory)")
)
tabla_ind_gt <- tab_options(
  tabla_ind_gt,
  table.border.top.style = "solid", table.border.top.color = "black", table.border.top.width = px(1),
  table.border.bottom.style = "solid", table.border.bottom.color = "black", table.border.bottom.width = px(1),
  column_labels.border.top.style = "solid", column_labels.border.top.color = "black", column_labels.border.top.width = px(1),
  column_labels.border.bottom.style = "solid", column_labels.border.bottom.color = "black", column_labels.border.bottom.width = px(1),
  table_body.hlines.style = "solid", table_body.hlines.color = "gray70", table_body.hlines.width = px(1),
  table_body.vlines.style = "solid", table_body.vlines.color = "gray70", table_body.vlines.width = px(1),
  row.striping.include_table_body = FALSE
)
tabla_ind_gt
Tabla Nro. 23
Indicadores estadísticos descriptivos de la variable Longitud Media para el estudio de los glaciares del mundo
Indicador Valor
Mínimo -179.92
Máximo 179.68
Media Aritmética 31.9
Mediana 75.48
Moda (Marca de clase) 75
Desviación Estándar 83.86
Varianza 7032.61
Coeficiente de Variación (%) 262.88
Cuartil 1 (Q1) -50.38
Cuartil 3 (Q3) 85.27
Rango Intercuartílico (RIC) 135.64
Coeficiente de Asimetría -0.87
Curtosis -0.52
Grupo: 1
Fuente: https://www.kaggle.com/datasets/nsidcorg/glacier-inventory