En esta sección se incorporan las librerías requeridas para realizar el procesamiento y análisis de la información.
setwd("C:/Users/HP/Desktop/tabla_petro")
library(readxl)
library(dplyr)
library(gt)
archivo <- list.files(pattern = "^tabla_transporte_petroleo.*\\.xlsx$")[1]
if (is.na(archivo)) stop("No se encontró el archivo .xlsx dentro de la carpeta tabla_petro")
datos <- read_excel(archivo, sheet = "Datos_10000")
colores <- list(
titulo = "#235347",
cabecera = "#DAF1DE",
texto = "#163832",
total = "#8EB69B",
barras = "#235347"
)
paleta <- function(n) colorRampPalette(c("#163832", "#235347", "#8EB69B", "#DAF1DE"))(n)
# Tabla de frecuencias: ni (absoluta), hi (porcentual) y fi (fracción)
frecuencias <- function(x, nombre) {
tab <- table(x)
tdf <- data.frame(categoria = names(tab), ni = as.numeric(tab), stringsAsFactors = FALSE)
tdf$hi <- round(tdf$ni / sum(tdf$ni) * 100, 5)
tdf$fi <- tdf$ni / sum(tdf$ni)
colnames(tdf)[1] <- nombre
tdf
}
# Agrega la fila Total
con_total <- function(tdf) {
total <- tdf[1, ]
total[1, 1] <- "Total"
total$ni <- sum(tdf$ni)
total$hi <- sum(tdf$hi)
total$fi <- sum(tdf$fi)
rbind(tdf, total)
}
# Tabla
tabla_gt <- function(tdfc, numero, titulo, subtitulo) {
gt(tdfc) %>%
tab_header(
title = md(paste0("**Tabla N°", numero, ": ", titulo, "**")),
subtitle = subtitulo) %>%
tab_spanner(label = md("**Frecuencia Relativa**"), columns = c(hi, fi)) %>%
cols_label(ni = md("**ni**"), hi = md("Porcentual (%)"), fi = md("Fracción")) %>%
fmt_number(columns = hi, decimals = 2) %>%
fmt_number(columns = fi, decimals = 4) %>%
cols_align(align = "center", columns = everything()) %>%
tab_style(
style = list(cell_fill(color = colores$titulo), cell_text(color = "white", weight = "bold")),
locations = cells_title()) %>%
tab_style(
style = list(cell_fill(color = colores$cabecera), cell_text(weight = "bold", color = colores$texto)),
locations = cells_column_labels()) %>%
tab_style(
style = list(cell_fill(color = colores$titulo), cell_text(color = "white", weight = "bold")),
locations = cells_column_spanners()) %>%
tab_style(
style = list(cell_fill(color = colores$total), cell_text(weight = "bold", color = colores$texto)),
locations = cells_body(rows = nrow(tdfc))) %>%
tab_options(
table.border.top.color = colores$titulo,
table.border.bottom.color = colores$titulo,
column_labels.border.bottom.color = colores$titulo,
data_row.padding = px(6),
table.font.size = px(13))
}
# Diagrama de barras (columna = "ni" o "hi")
barras <- function(tdf, columna, titulo, xlab, ylab, ylim = NULL) {
vertical <- max(nchar(as.character(tdf[[1]]))) > 12 || nrow(tdf) > 5
margen <- if (vertical) ceiling(max(nchar(as.character(tdf[[1]]))) * 0.45 + 3) else 5
par(mar = c(margen, 5, 5, 2))
barplot(tdf[[columna]], main = paste(strwrap(titulo, 72), collapse = "\n"),
xlab = "", ylab = ylab,
col = colores$barras, names.arg = tdf[[1]],
las = if (vertical) 2 else 1, cex.names = 1, cex.axis = 0.8, cex.main = 1,
ylim = ylim)
mtext(xlab, side = 1, line = margen - 1.5)
par(mar = c(5, 4, 4, 2) + 0.1)
}
# Diagrama circular
circular <- function(tdf, titulo, leyenda) {
cols <- paleta(nrow(tdf))
layout(matrix(1:2, nrow = 1), widths = c(3, 2.5))
par(mar = c(1, 3, 1, 3), oma = c(0, 0, 4, 0))
pie(tdf$hi, labels = paste0(round(tdf$hi, 2), "%"), col = cols,
radius = 0.75, cex = 1, init.angle = 90)
plot.new()
legend("center", legend = tdf[[1]], fill = cols, cex = 1, title = leyenda, bty = "n")
mtext(paste(strwrap(titulo, 72), collapse = "\n"), outer = TRUE, line = 0.5, font = 2, cex = 1)
layout(1)
par(mar = c(5, 4, 4, 2) + 0.1, oma = c(0, 0, 0, 0))
}
# Tabla de indicadores
indicadores_gt <- function(variable, moda, subtitulo) {
tabla <- data.frame(variable, "N/A", "N/A", "N/A", moda, "N/A", "N/A", "N/A", "N/A", "N/A", "N/A",
stringsAsFactors = FALSE)
names(tabla) <- c("Variable", "Rango [Min; Max]", paste0("Media (X", "\u0304", ")"), "Mediana (Me)",
"Moda (Mo)", paste0("Varianza (S", "\u00b2", ")"), "Desv. Est. (S)", "C.V. (%)",
"Asimetría (As)", "Curtosis (K)", "Valores Atípicos")
gt(tabla) %>%
tab_header(
title = md("**CONCLUSIONES Y ESTADÍSTICOS**"),
subtitle = subtitulo) %>%
tab_source_note(source_note = "Autor: *") %>%
cols_align(align = "center", columns = everything()) %>%
tab_style(
style = list(cell_fill(color = colores$titulo), cell_text(color = "white", weight = "bold")),
locations = cells_title()) %>%
tab_style(
style = list(cell_fill(color = colores$cabecera), cell_text(weight = "bold", color = colores$texto)),
locations = cells_column_labels()) %>%
tab_options(
table.border.top.color = colores$titulo,
table.border.bottom.color = colores$titulo,
column_labels.border.bottom.color = colores$titulo,
data_row.padding = px(6))
}
Este bloque revisa la estructura de la base de datos original.
dim(datos)
## [1] 10000 20
datos %>%
select(ID_registro, Fecha, Estado_operacion) %>%
glimpse()
## Rows: 10,000
## Columns: 3
## $ ID_registro <chr> "EC-PIPE-00248", "EC-PIPE-02975", "EC-PIPE-07780", "E…
## $ Fecha <chr> "2015-01-01", "2015-01-02", "2015-01-02", "2015-01-02…
## $ Estado_operacion <chr> "Operativo", "Operativo", "Operativo", "Operativo", "…
En esta sección se extrae la variable Estado_operacion para su posterior análisis.
Estado_operacion <- datos$Estado_operacion
TDF_Estado_operacion <- frecuencias(Estado_operacion, "Estado de operación")
head(TDF_Estado_operacion)
## Estado de operación ni hi fi
## 1 Intermitente 955 9.55 0.0955
## 2 Operativo 9045 90.45 0.9045
Se calculan las frecuencias absolutas (ni), porcentuales (hi) y relativas (fi), y se agrega la fila de totales.
TDF_Estado_operacion_completa <- con_total(TDF_Estado_operacion)
print(TDF_Estado_operacion_completa)
## Estado de operación ni hi fi
## 1 Intermitente 955 9.55 0.0955
## 2 Operativo 9045 90.45 0.9045
## 3 Total 10000 100.00 1.0000
tabla_gt(TDF_Estado_operacion_completa, 1,
"DISTRIBUCIÓN DE FRECUENCIAS DE LOS REGISTROS SEGÚN EL ESTADO DE OPERACIÓN",
"Distribución de los registros según la condición de funcionamiento del tramo")
| Tabla N°1: DISTRIBUCIÓN DE FRECUENCIAS DE LOS REGISTROS SEGÚN EL ESTADO DE OPERACIÓN | |||
| Distribución de los registros según la condición de funcionamiento del tramo | |||
| Estado de operación | ni |
Frecuencia Relativa
|
|
|---|---|---|---|
| Porcentual (%) | Fracción | ||
| Intermitente | 955 | 9.55 | 0.0955 |
| Operativo | 9045 | 90.45 | 0.9045 |
| Total | 10000 | 100.00 | 1.0000 |
barras(TDF_Estado_operacion, "ni",
"Gráfica N°1: Distribución de la cantidad de registros según estado de operación",
"Estado de operación", "Cantidad")
barras(TDF_Estado_operacion, "ni",
"Gráfica N°2: Distribución de la cantidad de registros según estado de operación",
"Estado de operación", "Cantidad", ylim = c(0, sum(TDF_Estado_operacion$ni)))
barras(TDF_Estado_operacion, "hi",
"Gráfica N°3: Distribución en porcentaje según estado de operación",
"Estado de operación", "Porcentaje")
barras(TDF_Estado_operacion, "hi",
"Gráfica N°4: Distribución en porcentaje según estado de operación",
"Estado de operación", "Porcentaje", ylim = c(0, 100))
circular(TDF_Estado_operacion,
"Gráfica N°5: Distribución porcentual de los registros según estado de operación",
"Estado de operación")
moda <- as.character(TDF_Estado_operacion[[1]][which.max(TDF_Estado_operacion$ni)])
indicadores_gt("Estado de operación", moda,
"Resumen de indicadores de estado de operación de los registros de operación")
| CONCLUSIONES Y ESTADÍSTICOS | ||||||||||
| Resumen de indicadores de estado de operación de los registros de operación | ||||||||||
| Variable | Rango [Min; Max] | Media (X̄) | Mediana (Me) | Moda (Mo) | Varianza (S²) | Desv. Est. (S) | C.V. (%) | Asimetría (As) | Curtosis (K) | Valores Atípicos |
|---|---|---|---|---|---|---|---|---|---|---|
| Estado de operación | N/A | N/A | N/A | Operativo | N/A | N/A | N/A | N/A | N/A | N/A |
| Autor: * | ||||||||||
El valor más frecuente de Estado de operación es Operativo, con 9045 registros (90.45 %).