# Configuración inicial
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE, fig.align = "center")
# Cargar librerías necesarias para el formato de tablas solicitado
library(knitr)
library(kableExtra)
library(dplyr)
# 1. CARGA DE DATOS (En una sola línea para evitar el error "unexpected string constant")
datos <- read.csv("C:/Users/Martin/Desktop/Estadistica/CMDB_Data.csv", header = TRUE, sep = ";", dec = ".", fileEncoding = "latin1")
# 2. LIMPIEZA DE TEXTO (Extraer solo números de COORDINATES_QUAL)
datos$COORDINATES_QUAL_CLEAN <- gsub("[^0-9.]", "", datos$COORDINATES_QUAL)
datos$COORDINATES_QUAL_NUM <- as.numeric(datos$COORDINATES_QUAL_CLEAN)
# 3. CREACIÓN DE LA VARIABLE ORDINAL
datos$CALIDAD_ORDINAL <- as.character(cut(datos$COORDINATES_QUAL_NUM,
breaks = c(-Inf, 1, 10, 100, 1000, Inf),
labels = c("1. Excelente (<=1m)",
"2. Muy Buena (<=10m)",
"3. Buena (<=100m)",
"4. Regular (<=1km)",
"5. Baja (>1km)")))
# 4. ASIGNACIÓN DE CASILLAS VACÍAS A "SIN REGISTRO"
datos$CALIDAD_ORDINAL[is.na(datos$CALIDAD_ORDINAL)] <- "6. Sin Registro"
datos$CALIDAD_ORDINAL[datos$COORDINATES_QUAL == ""] <- "6. Sin Registro"
datos$CALIDAD_ORDINAL[is.na(datos$COORDINATES_QUAL)] <- "6. Sin Registro"
# 5. CONVERTIR A FACTOR (Para mantener el orden estricto)
datos$CALIDAD_ORDINAL <- factor(datos$CALIDAD_ORDINAL,
levels = c("1. Excelente (<=1m)", "2. Muy Buena (<=10m)",
"3. Buena (<=100m)", "4. Regular (<=1km)",
"5. Baja (>1km)", "6. Sin Registro"))
Se cargaron y categorizaron correctamente los datos de calidad espacial, incluyendo los valores sin registro.
VARIABLE SELECCIONADA: COORDINATES_QUAL
# Seleccionar la versión ordinal de COORDINATES_QUAL para el análisis
variable_seleccionada <- datos$CALIDAD_ORDINAL
nombre_variable <- "COORDINATES_QUAL"
cat("Variable seleccionada:", nombre_variable, "\n")
## Variable seleccionada: COORDINATES_QUAL
cat("Categorías de precisión encontradas:\n")
## Categorías de precisión encontradas:
print(table(variable_seleccionada))
## variable_seleccionada
## 1. Excelente (<=1m) 2. Muy Buena (<=10m) 3. Buena (<=100m)
## 210 119 259
## 4. Regular (<=1km) 5. Baja (>1km) 6. Sin Registro
## 220 30 528
TABLA DE FRECUENCIAS COMPLETA
# Cargar las librerías necesarias
library(dplyr)
library(gt)
# 1. CONTAR LAS MUESTRAS POR RANGO ORDINAL
TDF_ORDINAL <- table(datos$CALIDAD_ORDINAL)
# 2. ESTRUCTURAR LA TABLA BASE
tabla_cordinal <- as.data.frame(TDF_ORDINAL)
colnames(tabla_cordinal) <- c("Rango_Precision", "ni")
# 3. CÁLCULO DE PROPORCIONES
total_muestras <- sum(tabla_cordinal$ni)
tabla_cordinal$hi <- tabla_cordinal$ni / total_muestras
tabla_cordinal$hi_porc <- round(tabla_cordinal$hi * 100, 2)
# 4. FRECUENCIAS ACUMULADAS (Ascendentes y Descendentes)
tabla_cordinal$Ni_asc <- cumsum(tabla_cordinal$ni)
tabla_cordinal$Hi_asc <- cumsum(tabla_cordinal$hi_porc)
tabla_cordinal$Ni_des <- rev(cumsum(rev(tabla_cordinal$ni)))
tabla_cordinal$Hi_des <- rev(cumsum(rev(tabla_cordinal$hi_porc)))
# 5. CREAR LA FILA DE TOTALES
Total <- data.frame(Rango_Precision = "TOTAL GENERAL",
ni = sum(tabla_cordinal$ni),
hi = sum(tabla_cordinal$hi),
hi_porc = sum(tabla_cordinal$hi_porc),
Ni_asc = NA, Hi_asc = NA, Ni_des = NA, Hi_des = NA)
# 6. UNIR TODO EN LA TABLA FINAL
tabla_final <- rbind(tabla_cordinal, Total)
# 7. MOSTRAR LA TABLA CON LA ESTÉTICA 'gt'
tabla_ord_gt <- tabla_final %>%
gt() %>%
tab_header(
title = md("**Tabla N° 1**"),
subtitle = md("Distribución de precisión de coordenadas en depósitos minerales")
) %>%
tab_source_note(
source_note = md("Autores: Grupo 1 <br> Semestre 2026 - 2026")
) %>%
fmt_missing(
columns = everything(),
missing_text = "-"
) %>%
tab_options(
table.border.top.color = "black",
table.border.bottom.color = "black",
heading.border.bottom.color = "black",
heading.border.bottom.width = px(2),
column_labels.border.top.color = "black",
column_labels.border.bottom.color = "black",
column_labels.border.bottom.width = px(2),
table_body.hlines.color = "gray",
table_body.border.bottom.color = "black",
row.striping.include_table_body = TRUE
)
# Renderizar la tabla en el documento
tabla_ord_gt
| Tabla N° 1 | |||||||
| Distribución de precisión de coordenadas en depósitos minerales | |||||||
| Rango_Precision | ni | hi | hi_porc | Ni_asc | Hi_asc | Ni_des | Hi_des |
|---|---|---|---|---|---|---|---|
| 1. Excelente (<=1m) | 210 | 0.15373353 | 15.37 | 210 | 15.37 | 1366 | 100.00 |
| 2. Muy Buena (<=10m) | 119 | 0.08711567 | 8.71 | 329 | 24.08 | 1156 | 84.63 |
| 3. Buena (<=100m) | 259 | 0.18960469 | 18.96 | 588 | 43.04 | 1037 | 75.92 |
| 4. Regular (<=1km) | 220 | 0.16105417 | 16.11 | 808 | 59.15 | 778 | 56.96 |
| 5. Baja (>1km) | 30 | 0.02196193 | 2.20 | 838 | 61.35 | 558 | 40.85 |
| 6. Sin Registro | 528 | 0.38653001 | 38.65 | 1366 | 100.00 | 528 | 38.65 |
| TOTAL GENERAL | 1366 | 1.00000000 | 100.00 | - | - | - | - |
| Autores: Grupo 1 Semestre 2026 - 2026 |
|||||||
REGISTROS CON PRECISIÓN FRENTE A REGISTROS SIN INFORMACIÓN
# Clasificar los datos según la disponibilidad de información de precisión
sin_registro <- as.numeric(TDF_ORDINAL["6. Sin Registro"])
con_registro <- sum(TDF_ORDINAL) - sin_registro
frecuencias_clasificadas <- c(
"Con precisión registrada" = con_registro,
"Sin registro" = sin_registro
)
tabla_clasificacion <- data.frame(
Clasificacion = names(frecuencias_clasificadas),
ni = as.numeric(frecuencias_clasificadas),
stringsAsFactors = FALSE
)
tabla_clasificacion$hi <- tabla_clasificacion$ni / sum(tabla_clasificacion$ni)
tabla_clasificacion$hi_porc <- round(tabla_clasificacion$hi * 100, 2)
Total_Clasificacion <- data.frame(
Clasificacion = "TOTAL GENERAL",
ni = sum(tabla_clasificacion$ni),
hi = sum(tabla_clasificacion$hi),
hi_porc = sum(tabla_clasificacion$hi_porc)
)
tabla_final_clasificacion <- rbind(
tabla_clasificacion,
Total_Clasificacion
)
tabla_final_clasificacion %>%
gt() %>%
fmt_number(columns = hi, decimals = 4) %>%
fmt_number(columns = hi_porc, decimals = 2) %>%
tab_header(
title = md("**Tabla N° 2**"),
subtitle = md("Disponibilidad de información sobre precisión de coordenadas")
) %>%
tab_source_note(
source_note = md("Autores: Grupo 1 <br> Semestre 2026 - 2026")
) %>%
tab_options(
table.border.top.color = "black",
table.border.bottom.color = "black",
heading.border.bottom.color = "black",
heading.border.bottom.width = px(2),
column_labels.border.bottom.color = "black",
row.striping.include_table_body = TRUE
)
| Tabla N° 2 | |||
| Disponibilidad de información sobre precisión de coordenadas | |||
| Clasificacion | ni | hi | hi_porc |
|---|---|---|---|
| Con precisión registrada | 838 | 0.6135 | 61.35 |
| Sin registro | 528 | 0.3865 | 38.65 |
| TOTAL GENERAL | 1366 | 1.0000 | 100.00 |
| Autores: Grupo 1 Semestre 2026 - 2026 |
|||
GRÁFICA DE BARRAS LOCAL Y GLOBAL
# Ajustar márgenes para que las etiquetas ordinales (que son largas) quepan correctamente
par(mar = c(10, 5, 4, 2) + 0.1)
limite_y_local <- max(TDF_ORDINAL) * 1.2
# 1. PRIMERA GRÁFICA (LOCAL)
barplot(TDF_ORDINAL,
main = "Gráfica 1: Calidad de Coordenadas (LOCAL)",
ylab = "Cantidad de depósitos",
col = "pink",
las = 2, # Textos en vertical
cex.names = 0.8,
ylim = c(0, limite_y_local))
# 2. SEGUNDA GRÁFICA (GLOBAL - EJE Y AL TOTAL DE DATOS USADOS)
# 'total_muestras' asegura que se compare contra el 100% de los registros
barplot(TDF_ORDINAL,
main = "Gráfica 2: Calidad de Coordenadas (GLOBAL)",
ylab = "Cantidad total de la base de datos",
col = "skyblue",
las = 2,
cex.names = 0.8,
ylim = c(0, total_muestras), # El techo es el total exacto
yaxt = "n")
# 3. Dibujar el eje Y personalizado anclado al total
puntos_eje <- unique(round(c(seq(0, total_muestras, length.out = 5), total_muestras)))
axis(2, at = puntos_eje, las = 1)
ANÁLISIS DE FRECUENCIA ABSOLUTA
par(mar = c(10, 5, 4, 2) + 0.1)
freq_abs <- TDF_ORDINAL
# 2. DIBUJAR LA GRÁFICA Y GUARDAR SUS COORDENADAS
bar_centers <- barplot(freq_abs,
main = "Gráfica 3: Frecuencia Absoluta",
ylab = "Cantidad",
col = "orange",
las = 2,
cex.names = 0.8,
ylim = c(0, max(freq_abs) * 1.2))
# 3. PONER LAS ETIQUETAS NUMÉRICAS ENCIMA DE LAS BARRAS
text(x = bar_centers,
y = freq_abs,
labels = freq_abs,
pos = 3,
cex = 0.8,
col = "black")
ANÁLISIS DE FRECUENCIA RELATIVA (PORCENTAJES)
par(mar = c(10, 5, 4, 2) + 0.1)
# 1. USAR LOS DATOS DE LA TABLA (Porcentajes)
freq_rel_porc <- tabla_cordinal$hi_porc
# 2. DIBUJAR LAS BARRAS Y PERSONALIZAR EL LIENZO
bar_centers_rel <- barplot(freq_rel_porc,
names.arg = tabla_cordinal$Rango_Precision,
main = "Gráfica 4: Distribución Porcentual Relativa (%)",
ylab = "Porcentaje del Total (%)",
col = "orchid",
las = 2,
cex.names = 0.8,
ylim = c(0, max(freq_rel_porc) * 1.3),
yaxt = "n",
yaxs = "i")
# 3. CONSTRUIR UN EJE Y PERSONALIZADO
axis(2, at = seq(0, max(freq_rel_porc) + 5, length.out = 5),
labels = paste0(round(seq(0, max(freq_rel_porc) + 5, length.out = 5), 1), "%"),
las = 1, cex.axis = 0.8)
# 4. COLOCAR LAS ETIQUETAS CON EL SÍMBOLO "%" EN LAS BARRAS
text(x = bar_centers_rel,
y = freq_rel_porc,
labels = paste0(freq_rel_porc, "%"),
pos = 3,
cex = 0.8,
col = "black")
GRÁFICA CIRCULAR
# 1. ALISTAR DATOS Y COLORES
colores <- terrain.colors(length(TDF_ORDINAL))
etiquetas_leyenda <- paste0(tabla_cordinal$Rango_Precision, " (", tabla_cordinal$hi_porc, "%)")
# Filtrar etiquetas internas del pie chart (Si hay valores en 0%, las vaciamos para limpieza visual)
etiquetas_pie <- paste0(tabla_cordinal$hi_porc, "%")
etiquetas_pie[tabla_cordinal$hi_porc == 0] <- ""
# 2. AJUSTAR EL LIENZO DE TRABAJO
par(mar = c(2, 2, 3, 16), xpd = TRUE)
# 3. DIBUJAR LA GRÁFICA CIRCULAR
pie(TDF_ORDINAL,
labels = etiquetas_pie,
col = colores,
main = "Gráfica 5: Composición de Calidad de Datos",
radius = 0.9,
cex = 0.8)
# 4. MARCAR LAS COORDENADAS DEL CUADRO DE LEYENDA
x0 <- 1.1
x1 <- 3.5
y1 <- 0.9
y0 <- -0.5
# 5. DIBUJAR EL CUADRO BLANCO DE FONDO
rect(xleft = x0, ybottom = y0, xright = x1, ytop = y1, col = "white", border = "black")
# 6. PONER EL TÍTULO DENTRO DE LA TARJETA
text(x = (x0 + x1)/2, y = y1 - 0.15, labels = "Precisión", font = 2, cex = 1.0)
# 7. LLENAR LA TARJETA CON LOS COLORES Y PORCENTAJES
legend(x = (x0 + x1)/2,
y = y1 - 0.25,
legend = etiquetas_leyenda,
fill = colores,
cex = 0.75,
bty = "n",
xjust = 0.5,
y.intersp = 1.4)
CONCLUSIÓN DE LA VARIABLE COORDINATES_QUAL
El análisis de la variable COORDINATES_QUAL confirma que la categoría de precisión más frecuente es 6. Sin Registro, que representa el 38.65% de los registros. Esta tendencia permite identificar la condición predominante de la información espacial y evidencia la importancia de validar la precisión de las coordenadas antes de realizar análisis geoquímicos, cartográficos o predictivos.