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 de 1.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 Ancho Medio (priorizando 'mean' y 'width', o 'width' en general)
cols_ancho_medio <- names(datos)[grepl("(mean.*width|width.*mean|ancho.*medio|medio.*ancho)", names(datos), ignore.case = TRUE)]
if (length(cols_ancho_medio) == 0) {
  cols_ancho_medio <- names(datos)[grepl("width", names(datos), ignore.case = TRUE)]
}
if (length(cols_ancho_medio) == 0) {
  print(names(datos))
  stop("No se encontró columna relacionada con Ancho Medio. Revisa los nombres impresos arriba.")
}

col_elegida <- cols_ancho_medio[1]
message("Usando columna: ", col_elegida)

ANCHO_MED_raw <- suppressWarnings(as.numeric(gsub(",", ".", trimws(as.character(datos[[col_elegida]])))))
ANCHO_MED <- ANCHO_MED_raw[is.finite(ANCHO_MED_raw)]

if (length(ANCHO_MED) == 0) {
  stop("La columna de Ancho Medio no contiene valores numéricos finitos.")
}

2. Tabla de distribución de frecuencias

# 3. Definir límites e intervalos (9 intervalos de amplitud constante)
min_val <- min(ANCHO_MED)
max_val <- max(ANCHO_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(ANCHO_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. 20)
TDF_ANCHO_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_ANCHO_MED_tabla <- rbind(TDF_ANCHO_MED, fila_totales)

tabla_freq_gt <- gt(TDF_ANCHO_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. 20",
  subtitle = "Distribución de frecuencia de la variable Ancho Medio 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. 20
Distribución de frecuencia de la variable Ancho Medio agrupada por intervalos, estudio de los glaciares del mundo
Intervalo MC ni hi Ni ↑ Ni ↓ Hi ↑ Hi ↓
[0 - 5) 2.5 69782 99.74 69782 69966 99.74 99.99
[5 - 10) 7.5 143 0.20 69925 184 99.94 0.25
[10 - 15) 12.5 29 0.04 69954 41 99.98 0.05
[15 - 20) 17.5 6 0.01 69960 12 99.99 0.01
[20 - 25) 22.5 3 0.00 69963 6 99.99 0
[25 - 30] 27.5 3 0.00 69966 3 99.99 0
Totales - 69966 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(ANCHO_MED, breaks = limites, col = "steelblue", border = "white",
     main = "Gráfico Nro. 1: Ancho Medio 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 = "Ancho Medio (km)", line = 4.5)
title(ylab = "Cantidad", line = 4.5)

Gráfico 2: Histograma

par(mar = c(6, 6.5, 4, 2))
hist(ANCHO_MED, breaks = limites, col = "steelblue", border = "white",
     main = "Gráfico Nro. 2: Ancho Medio 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 = "Ancho Medio (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: Ancho Medio 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 Ancho Medio (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: Ancho Medio 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 Ancho Medio (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 Ancho Medio, en el estudio de los glaciares del mundo",
     xlab = "Marca de Clase - Ancho Medio (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(ANCHO_MED, horizontal = TRUE, col = "lightskyblue", border = "navy",
        main = "Gráfico Nro. 6: Diagrama de Caja de Ancho Medio, en el estudio de los glaciares del mundo",
        xlab = "Ancho Medio (km)", las = 1)

4. Indicadores Estadísticos

# 6. Indicadores estadísticos (Tabla Nro. 21)
n_am       <- length(ANCHO_MED)
min_am     <- round(min(ANCHO_MED), 2)
max_am     <- round(max(ANCHO_MED), 2)
media      <- round(mean(ANCHO_MED), 2)
mediana    <- round(median(ANCHO_MED), 2)
moda_aprox <- round(mc_vec[which.max(ni_vec)], 2)
sd_am      <- if (n_am > 1) round(sd(ANCHO_MED), 2) else 0
var_am     <- if (n_am > 1) round(var(ANCHO_MED), 2) else 0
cv_am      <- if (!is.na(media) && media != 0) round((sd_am / abs(media)) * 100, 2) else NA
q1         <- round(quantile(ANCHO_MED, 0.25), 2)
q3         <- round(quantile(ANCHO_MED, 0.75), 2)
riq        <- round(IQR(ANCHO_MED), 2)
asimetria  <- if (n_am > 2 && sd_am > 0) round(sum((ANCHO_MED - mean(ANCHO_MED))^3) / (n_am * sd(ANCHO_MED)^3), 2) else NA
curtosis   <- if (n_am > 3 && sd_am > 0) round(sum((ANCHO_MED - mean(ANCHO_MED))^4) / (n_am * sd(ANCHO_MED)^4) - 3, 2) else NA

indicadores_ancho_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_am, max_am, media, mediana, moda_aprox,
    sd_am, var_am, cv_am,
    q1, q3, riq,
    asimetria, curtosis
  )),
  stringsAsFactors = FALSE
)

tabla_ind_gt <- gt(indicadores_ancho_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. 21",
  subtitle = "Indicadores estadísticos descriptivos de la variable Ancho Medio 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. 21
Indicadores estadísticos descriptivos de la variable Ancho Medio para el estudio de los glaciares del mundo
Indicador Valor
Mínimo 0
Máximo 29.8
Media Aritmética 0.56
Mediana 0.4
Moda (Marca de clase) 2.5
Desviación Estándar 0.64
Varianza 0.41
Coeficiente de Variación (%) 114.29
Cuartil 1 (Q1) 0.3
Cuartil 3 (Q3) 0.7
Rango Intercuartílico (RIC) 0.4
Coeficiente de Asimetría 12.19
Curtosis 322.03
Grupo: 1
Fuente: https://www.kaggle.com/datasets/nsidcorg/glacier-inventory