# 1. CARGA DE LIBRERÍAS (Silenciadas para el informe)
suppressPackageStartupMessages(library(tidyverse))
suppressPackageStartupMessages(library(readxl))
# 2. CARGAR EL ARCHIVO
# Mantenemos tu ruta original
# Al ejecutar esto, selecciona tu archivo manualmente en la ventana que se abre
Datos <- read_excel(file.choose(), sheet = "Dataset_Mundial_Final")
# 3. VERIFICAR DATOS
str(Datos)## tibble [58.978 × 29] (S3: tbl_df/tbl/data.frame)
## $ OBJECTID : num [1:58978] 2 3 4 5 6 7 8 9 10 11 ...
## $ code : chr [1:58978] "00001-AFG-P" "00002-AFG-P" "00003-AFG-P" "00004-AFG-P" ...
## $ plant_name : chr [1:58978] "Badghis Solar Power Plant" "Balkh solar farm" "Behsood solar farm" "Dab Pal 4 solar farm" ...
## $ country : chr [1:58978] "Afghanistan" "Afghanistan" "Afghanistan" "Afghanistan" ...
## $ operational_status : chr [1:58978] "cancelled - inferred 4 y" "cancelled - inferred 4 y" "cancelled - inferred 4 y" "shelved - inferred 2 y" ...
## $ longitude : num [1:58978] 62,9 67,1 70,4 66,2 65,7 ...
## $ latitude : num [1:58978] 35,1 36,7 34,4 33,8 31,7 ...
## $ elevation : num [1:58978] 918 359 629 2288 1060 ...
## $ area : num [1:58978] 6,74 10,72 487,73 111,8 1929,96 ...
## $ size : chr [1:58978] "Small" "Small" "Small" "Small" ...
## $ slope : num [1:58978] 7,38 0,49 1,1 6,16 1,23 ...
## $ slope_type : chr [1:58978] "Moderado" "Plano o casi plano" "Plano o casi plano" "Moderado" ...
## $ curvature : num [1:58978] -0,024 0 0 0,045 -0,005 -0,005 -0,015 0 0 -0,009 ...
## $ curvature_type : chr [1:58978] "Superficies cóncavas / Valles" "Superficies planas o intermedias" "Superficies planas o intermedias" "Superficies convexas / Crestas" ...
## $ aspect : num [1:58978] 96,8 358,5 36,2 305,8 248,4 ...
## $ aspect_type : chr [1:58978] "East" "North" "Northeast" "Northwest" ...
## $ dist_to_road : num [1:58978] 7037,1 92,7 112,1 1705,3 115,8 ...
## $ ambient_temperature : num [1:58978] 14,4 17,88 21,32 8,86 19,64 ...
## $ ghi : num [1:58978] 5,82 5,58 5,8 6,75 6,62 ...
## $ humidity : num [1:58978] 47,7 42,3 36,4 37,3 24,2 ...
## $ wind_speed : num [1:58978] 0,039 0,954 0,234 0,943 0,37 ...
## $ wind_direction : num [1:58978] 187,5 207,4 255,6 160,3 97,7 ...
## $ dt_wind : chr [1:58978] "South" "Southwest" "West" "South" ...
## $ solar_aptitude : num [1:58978] 0,72 0,635 0,685 0,659 0,819 0,819 0,818 0,642 0,63 0,374 ...
## $ solar_aptitude_rounded: num [1:58978] 7 6 7 7 8 8 8 6 6 4 ...
## $ solar_aptittude_class : chr [1:58978] "Alta" "Alta" "Alta" "Alta" ...
## $ capacity : num [1:58978] 32 40 60 3000 100 100 36 50 25 100 ...
## $ optimal_tilt : num [1:58978] 30 31 31,1 33 31 ...
## $ pv_potential : num [1:58978] 4,61 4,41 4,57 5,42 5,17 ...
# 1. CARGAR LIBRERIAS (Silenciadas para evitar anuncios en el informe)
suppressPackageStartupMessages(library(gt))
suppressPackageStartupMessages(library(dplyr))
# 2. CALCULOS DE FRECUENCIAS PARA HUMEDAD
# Filtramos valores nulos de la variable original
humedad_datos <- na.omit(Datos$humidity)
n_hum <- length(humedad_datos)
K_hum <- floor(1 + 3.322 * log10(n_hum))
min_hum <- min(humedad_datos)
max_hum <- max(humedad_datos)
# Definicion de limites (Regla de Sturges)
breaks_hum <- seq(min_hum, max_hum, length.out = K_hum + 1)
lim_inf_h <- breaks_hum[1:K_hum]
lim_sup_h <- breaks_hum[2:(K_hum+1)]
MC_h <- (lim_inf_h + lim_sup_h) / 2
# Frecuencias simples
ni_h <- as.vector(table(cut(humedad_datos, breaks = breaks_hum, right = FALSE, include.lowest = TRUE)))
hi_h <- (ni_h / sum(ni_h)) * 100
# --- CÁLCULO DE FRECUENCIAS ACUMULADAS ---
Ni_asc_h <- cumsum(ni_h)
Ni_desc_h <- rev(cumsum(rev(ni_h)))
Hi_asc_h <- cumsum(hi_h)
Hi_desc_h <- rev(cumsum(rev(hi_h)))
# ------------------------------------------------
# 3. CONSTRUCCION DEL DATAFRAME (Sin fila de totales)
df_tabla_hum <- data.frame(
Li = sprintf("%.2f", lim_inf_h),
Ls = sprintf("%.2f", lim_sup_h),
MC = sprintf("%.2f", MC_h),
ni = as.character(ni_h),
hi = sprintf("%.2f", hi_h),
Ni_asc = as.character(Ni_asc_h),
Ni_desc = as.character(Ni_desc_h),
Hi_asc = sprintf("%.2f", Hi_asc_h),
Hi_desc = sprintf("%.2f", Hi_desc_h),
stringsAsFactors = FALSE
)
# 4. GENERACION DE LA TABLA GT CON UNICODE
# \u00ba = º | \u00d3 = Ó | \u00cd = Í
df_tabla_hum %>%
gt() %>%
tab_header(
title = md("**TABLA N\u00ba 1: DISTRIBUCI\u00d3N DE FRECUENCIAS DE HUMEDAD**")
) %>%
cols_label(
Li = "Lim. Inf",
Ls = "Lim. Sup",
MC = "Marca Clase (Xi)",
ni = "ni",
hi = "hi (%)",
Ni_asc = "Ni Asc.",
Ni_desc = "Ni Desc.",
Hi_asc = "Hi Asc. (%)",
Hi_desc = "Hi Desc. (%)"
) %>%
cols_align(align = "center", columns = everything()) %>%
tab_style(
style = list(cell_fill(color = "white"), cell_text(color = "#4F4F4F", weight = "bold")),
locations = cells_title()
) %>%
tab_style(
style = list(cell_fill(color = "#F0F0F0"), cell_text(weight = "bold", color = "#4F4F4F")),
locations = cells_column_labels()
) %>%
tab_options(
table.border.top.color = "#D3D3D3",
table.border.bottom.color = "#D3D3D3",
column_labels.border.bottom.color = "#D3D3D3",
data_row.padding = px(6)
)| TABLA Nº 1: DISTRIBUCIÓN DE FRECUENCIAS DE HUMEDAD | ||||||||
| Lim. Inf | Lim. Sup | Marca Clase (Xi) | ni | hi (%) | Ni Asc. | Ni Desc. | Hi Asc. (%) | Hi Desc. (%) |
|---|---|---|---|---|---|---|---|---|
| 0.00 | 5.94 | 2.97 | 3 | 0.01 | 3 | 58978 | 0.01 | 100.00 |
| 5.94 | 11.88 | 8.91 | 17 | 0.03 | 20 | 58975 | 0.03 | 99.99 |
| 11.88 | 17.81 | 14.84 | 52 | 0.09 | 72 | 58958 | 0.12 | 99.97 |
| 17.81 | 23.75 | 20.78 | 224 | 0.38 | 296 | 58906 | 0.50 | 99.88 |
| 23.75 | 29.69 | 26.72 | 704 | 1.19 | 1000 | 58682 | 1.70 | 99.50 |
| 29.69 | 35.62 | 32.66 | 684 | 1.16 | 1684 | 57978 | 2.86 | 98.30 |
| 35.62 | 41.56 | 38.59 | 974 | 1.65 | 2658 | 57294 | 4.51 | 97.14 |
| 41.56 | 47.50 | 44.53 | 1643 | 2.79 | 4301 | 56320 | 7.29 | 95.49 |
| 47.50 | 53.44 | 50.47 | 3138 | 5.32 | 7439 | 54677 | 12.61 | 92.71 |
| 53.44 | 59.38 | 56.41 | 4431 | 7.51 | 11870 | 51539 | 20.13 | 87.39 |
| 59.38 | 65.31 | 62.34 | 6707 | 11.37 | 18577 | 47108 | 31.50 | 79.87 |
| 65.31 | 71.25 | 68.28 | 13957 | 23.66 | 32534 | 40401 | 55.16 | 68.50 |
| 71.25 | 77.19 | 74.22 | 19331 | 32.78 | 51865 | 26444 | 87.94 | 44.84 |
| 77.19 | 83.12 | 80.16 | 6603 | 11.20 | 58468 | 7113 | 99.14 | 12.06 |
| 83.12 | 89.06 | 86.09 | 503 | 0.85 | 58971 | 510 | 99.99 | 0.86 |
| 89.06 | 95.00 | 92.03 | 7 | 0.01 | 58978 | 7 | 100.00 | 0.01 |
# 1. PREPARACIÓN DE LA VARIABLE
col_lila <- "#B0C4DE"
hum_variable <- na.omit(Datos$humidity)
# Cálculos base
n_hum <- length(hum_variable)
K_hum <- floor(1 + 3.322 * log10(n_hum))
min_hum <- min(hum_variable)
max_hum <- max(hum_variable)
breaks_hum <- seq(min_hum, max_hum, length.out = K_hum + 1)
# 2. CREACIÓN DEL OBJETO HISTOGRAMA
par(mar = c(6, 5, 4, 2))
h_hum <- hist(hum_variable, breaks = breaks_hum, plot = FALSE, right = FALSE)
# --- PASO CLAVE: DE ni (Absoluta) A hi (Relativa %) ---
# Reemplazamos los conteos por porcentajes
h_hum$counts <- (h_hum$counts / n_hum) * 100
# 3. GRÁFICO EN PORCENTAJE (h_i)
# \u00e1 = á | \u00ba = º | \u00f3 = ó
plot(h_hum,
main = "Gr\u00e1fica N\u00ba 1: Distribuci\u00f3n de Frecuencias Relativas",
xlab = "Humedad",
ylab = "Frecuencia Relativa (%)",
col = col_lila,
border = "white",
axes = FALSE,
ylim = c(0, max(h_hum$counts) * 1.2))
# 4. EJES Y ESTÉTICA
axis(2, las = 2, cex.axis = 0.8)
# Eje X con los cortes exactos de la TDF
axis(1, at = breaks_hum, labels = round(breaks_hum, 2), las = 2, cex.axis = 0.7)
grid(nx = NA, ny = NULL, col = "#D7DBDD", lty = "dotted")# 1. DEFINICIÓN DE VARIABLES Y CORTES
col_lila <- "#B0C4DE"
col_rojo <- "#C0392B"
# Extraemos la variable
hum_variable <- na.omit(Datos$humidity)
# Lógica de la tabla
n_hum <- length(hum_variable)
K_hum <- floor(1 + 3.322 * log10(n_hum))
min_hum <- min(hum_variable)
max_hum <- max(hum_variable)
breaks_hum <- seq(min_hum, max_hum, length.out = K_hum + 1)
# 2. PREPARACIÓN DEL HISTOGRAMA
par(mar = c(6, 5, 4, 2))
h_hum <- hist(hum_variable, breaks = breaks_hum, plot = FALSE, right = FALSE)
# --- TRANSFORMACIÓN A FRECUENCIA RELATIVA (Hi %) ---
h_hum$counts <- (h_hum$counts / n_hum) * 100
# 3. GRÁFICO EN ESCALA DE Hi
# \u00e1 = á | \u00ba = º | \u00f3 = ó
plot(h_hum,
main = "Gr\u00e1fica N\u00ba 2: Distribuci\u00f3n General de la Humedad",
xlab = "Humedad (%)",
ylab = "Frecuencia Relativa (%)",
col = col_lila,
border = "white",
axes = FALSE,
ylim = c(0, max(h_hum$counts) * 1.2))
# 4. EJES Y DETALLES ESTÉTICOS
axis(2, las = 2, cex.axis = 0.8)
axis(1, at = breaks_hum, labels = round(breaks_hum, 2), las = 2, cex.axis = 0.7)
grid(nx = NA, ny = NULL, col = "#D7DBDD", lty = "dotted")
# 5. LÍNEA DE CORTE (Sincronizada en 29.69)
abline(v = 29.69, col = col_rojo, lwd = 3, lty = 2)
# Leyenda corregida con el valor de corte 29.69
legend("topright",
legend = paste("Punto de corte:", 29.69),
col = col_rojo, lty = 2, lwd = 3, bty = "n", cex = 0.7)# --- SEGMENTO 1: HUMEDAD BAJA (Menor o igual a 29.69) ---
# 1. FILTRADO DE DATOS
hum_s1 <- hum_variable[hum_variable <= 29.69]
# 2. PREPARACIÓN DEL HISTOGRAMA (Usando breaks originales)
par(mar = c(6, 5, 4, 2))
h_s1 <- hist(hum_s1, breaks = breaks_hum, plot = FALSE, right = FALSE)
# --- TRANSFORMACIÓN A FRECUENCIA RELATIVA (Hi %) ---
# Dividimos para n_hum (total de la muestra) para mantener la escala global
h_s1$counts <- (h_s1$counts / n_hum) * 100
# 3. GRÁFICO DEL SEGMENTO 1 EN PORCENTAJE
# \u00e1 = á | \u2264 = ≤ | \u00ba = º
plot(h_s1,
main = "Gr\u00e1fica N\u00ba 3: Segmento 1 - Humedad Baja",
xlab = "Humedad (%)",
ylab = "Frecuencia Relativa (%)",
col = "#B0C4DE",
border = "white",
axes = FALSE,
xlim = c(min_hum, 29.69),
ylim = c(0, max(h_s1$counts) * 1.2))
# 4. EJES Y ESTÉTICA
axis(2, las = 2, cex.axis = 0.7)
# Mostramos los cortes que corresponden a este segmento
breaks_s1 <- breaks_hum[breaks_hum <= 31]
axis(1, at = breaks_s1, labels = round(breaks_s1, 2), las = 2, cex.axis = 0.6)
grid(nx = NA, ny = NULL, col = "#D7DBDD", lty = "dotted")# --- SEGMENTO 2: HUMEDAD ALTA (Mayor a 29.69) ---
# 1. FILTRADO DE DATOS
hum_s2 <- hum_variable[hum_variable > 29.69]
# 2. PREPARACIÓN DEL HISTOGRAMA (Mantenemos breaks originales)
par(mar = c(6, 5, 4, 2))
h_s2 <- hist(hum_s2, breaks = breaks_hum, plot = FALSE, right = FALSE)
# --- TRANSFORMACIÓN A FRECUENCIA RELATIVA (Hi %) ---
# Dividimos para n_hum para mantener la proporción global del estudio
h_s2$counts <- (h_s2$counts / n_hum) * 100
# 3. GRÁFICO DEL SEGMENTO 2 EN PORCENTAJE
# \u00e1 = á | \u00ba = º | \u00f3 = ó
plot(h_s2,
main = "Gr\u00e1fica N\u00ba 4: Segmento 2 - Humedad Alta",
xlab = "Humedad (%)",
ylab = "Frecuencia Relativa (%)",
col = "#B0C4DE",
border = "white",
axes = FALSE,
xlim = c(29.69, max_hum),
ylim = c(0, max(h_s2$counts) * 1.2))
# 4. EJES Y ESTÉTICA
axis(2, las = 2, cex.axis = 0.7)
# Mostramos los cortes que corresponden a la humedad alta
breaks_s2 <- breaks_hum[breaks_hum >= 29]
axis(1, at = breaks_s2, labels = round(breaks_s2, 2), las = 2, cex.axis = 0.6)
grid(nx = NA, ny = NULL, col = "#D7DBDD", lty = "dotted")# --- SEGMENTO 1: HUMEDAD BAJA CON MODELO WEIBULL REFLEJADO (Hi %) ---
# 1. CARGA SILENCIOSA DE LIBRERÍAS
suppressPackageStartupMessages(library(MASS))
# 2. FILTRADO Y PREPARACIÓN DE DATOS
hum_s1 <- hum_variable[hum_variable <= 29.69]
# Transformación para reflejar la curva
datos_ref_s1 <- 29.69 - hum_s1 + 0.01
# 3. AJUSTE DEL MODELO
fit_s1 <- suppressWarnings(fitdistr(datos_ref_s1, "weibull",
start = list(shape = 1.5, scale = mean(datos_ref_s1))))
shape_s1 <- as.numeric(fit_s1$estimate["shape"])
scale_s1 <- as.numeric(fit_s1$estimate["scale"])
# 4. PREPARACIÓN DEL HISTOGRAMA (Cálculo interno)
h_s1 <- hist(hum_s1, breaks = breaks_hum, plot = FALSE, right = FALSE)
# --- TRANSFORMACIÓN SEGURA A PORCENTAJE ---
h_s1$counts <- (h_s1$counts / n_hum) * 100
h_s1$density <- h_s1$counts / sum(h_s1$counts) # Sincronización para evitar error en plot
# 5. GRÁFICO DEL SEGMENTO
par(mar = c(6, 5, 4, 2))
plot(h_s1,
freq = TRUE, # Forzamos uso de counts porcentuales
main = "Gr\u00e1fica N\u00ba 5: Ajuste Weibull Reflejado",
xlab = "Humedad (%)",
ylab = "Frecuencia Relativa (%)",
col = "#B0C4DE", border = "white",
axes = FALSE,
xlim = c(min_hum, 29.69),
ylim = c(0, max(h_s1$counts, na.rm = TRUE) * 1.3))
# 6. CURVA TEÓRICA
x_c <- seq(min_hum, 29.69, length.out = 200)
y_densidad <- dweibull(29.69 - x_c + 0.01, shape = shape_s1, scale = scale_s1)
ancho_barra <- breaks_hum[2] - breaks_hum[1]
y_final <- y_densidad * ancho_barra * 100 * (length(hum_s1) / n_hum)
lines(x_c, y_final, col = "#C0392B", lwd = 3)
# 7. EJES Y ESTÉTICA
axis(2, las = 2, cex.axis = 0.7)
breaks_ver <- breaks_hum[breaks_hum <= 31]
axis(1, at = breaks_ver, labels = round(breaks_ver, 2), las = 2, cex.axis = 0.6)
grid(nx = NA, ny = NULL, col = "#D7DBDD", lty = "dotted")
# 8. LEYENDA
legend("topleft",
legend = c("Datos Emp\u00edricos", "Conjetura Weibull Ref."),
fill = c("#B0C4DE", NA), border = c("white", NA),
col = c(NA, "#C0392B"), lty = c(NA, 1), lwd = c(NA, 3),
bty = "n", cex = 0.7)# --- TEST PARA SEGMENTO 1 (Humedad - Weibull Reflejada) ---
# 1. DEFINICIÓN DE CORTES PARA EL SEGMENTO 1
# Filtramos los breaks originales para que solo lleguen hasta el punto de corte
cortes_s1 <- breaks_hum[breaks_hum <= 29.69]
# Si el último corte es menor a 29.69, lo agregamos para cerrar el intervalo
if(max(cortes_s1) < 29.69) cortes_s1 <- c(cortes_s1, 29.69)
# 2. PREPARACIÓN DE DATOS
n1 <- length(hum_s1)
K1 <- length(cortes_s1) - 1
probs_w <- numeric(K1)
# 3. CÁLCULO DE PROBABILIDADES TEÓRICAS
for(i in 1:K1) {
# Reflejamos los límites usando el punto de corte de humedad
lim_inf_ref <- (29.69 + 0.01) - cortes_s1[i+1]
lim_sup_ref <- (29.69 + 0.01) - cortes_s1[i]
probs_w[i] <- pweibull(lim_sup_ref, shape = shape_s1, scale = scale_s1) -
pweibull(lim_inf_ref, shape = shape_s1, scale = scale_s1)
}
# Normalización
probs_w <- probs_w / sum(probs_w)
n_base <- 100
# 4. FRECUENCIAS OBSERVADAS Y ESPERADAS
# Usamos cortes_s1 para agrupar los datos
Fo1 <- as.vector(table(cut(hum_s1, breaks = cortes_s1, right = FALSE))) * (n_base / n1)
Fe1 <- probs_w * n_base
# 5. ESTADÍSTICOS DE VALIDACIÓN
chi1 <- sum((Fo1 - Fe1)^2 / Fe1)
crit1 <- qchisq(0.95, max(1, K1 - 1 - 2))
res1 <- if(chi1 < crit1) "APROBADO" else "RECHAZADO"
pear1 <- cor(Fo1, Fe1) * 100
# 6. IMPRESIÓN DE RESULTADOS
cat("Segmento 1 (Humedad Baja - Weibull Reflejado):\n")## Segmento 1 (Humedad Baja - Weibull Reflejado):
## Resultado Chi-cuadrado: APROBADO
## Chi-calc: 0,19 | Chi-crit: 7,81
## Correlación de Pearson: 99,99 %
# --- SEGMENTO 2: MODELO WEIBULL (Humedad Alta > 29.69%) ---
library(MASS)
# 1. FILTRADO Y PREPARACIÓN
hum_s2 <- hum_variable[hum_variable > 29.69]
# 2. AJUSTE DEL MODELO (Silenciando advertencias de NaNs)
fit_s2_weibull <- suppressWarnings(fitdistr(hum_s2, "weibull",
start = list(shape = 5, scale = mean(hum_s2))))
shape_w2 <- as.numeric(fit_s2_weibull$estimate["shape"])
scale_w2 <- as.numeric(fit_s2_weibull$estimate["scale"])
# 3. PREPARACIÓN DEL HISTOGRAMA
par(mar = c(6, 5, 4, 2))
h_s2 <- hist(hum_s2, breaks = breaks_hum, plot = FALSE, right = FALSE)
# --- CAMBIO A PORCENTAJE (Hi) ---
h_s2$counts <- (h_s2$counts / n_hum) * 100
# 4. GRÁFICO
# \u00ba = º | \u00f3 = ó
plot(h_s2,
main = "Gr\u00e1fica N\u00ba 6: Ajuste Modelo Weibull",
xlab = "Humedad (%)",
ylab = "Frecuencia Relativa (%)",
col = "#B0C4DE", border = "white",
axes = FALSE,
xlim = c(29.69, max_hum),
ylim = c(0, max(h_s2$counts) * 1.3))
# 5. CURVA TEÓRICA (Escalada a Porcentaje)
x_c2 <- seq(29.69, max_hum, length.out = 200)
y_densidad2 <- dweibull(x_c2, shape = shape_w2, scale = scale_w2)
# Escalamos la densidad para que coincida con el porcentaje del eje Y
ancho_barra <- breaks_hum[2] - breaks_hum[1]
y_final2 <- y_densidad2 * ancho_barra * 100 * (length(hum_s2) / n_hum)
lines(x_c2, y_final2, col = "#C0392B", lwd = 3)
# 6. EJES Y ESTÉTICA
axis(2, las = 2, cex.axis = 0.7)
breaks_ver2 <- breaks_hum[breaks_hum >= 29]
axis(1, at = breaks_ver2, labels = round(breaks_ver2, 2), las = 2, cex.axis = 0.6)
grid(nx = NA, ny = NULL, col = "#D7DBDD", lty = "dotted")
# 7. LEYENDA
legend("topright",
legend = c("Datos Emp\u00edricos", "Conjetura Weibull"),
fill = c("#B0C4DE", NA), border = c("white", NA),
col = c(NA, "#C0392B"), lty = c(NA, 1), lwd = c(NA, 3),
bty = "n", cex = 0.7)# --- TEST PARA SEGMENTO 2: Humedad Alta (Weibull) ---
# 1. PARÁMETROS BASE
n2 <- length(hum_s2)
cortes_s2 <- breaks_hum[breaks_hum >= 29.69]
if(min(cortes_s2) > 29.69) cortes_s2 <- c(29.69, cortes_s2)
K2 <- length(cortes_s2) - 1
probs2 <- numeric(K2)
# 2. CÁLCULO DE PROBABILIDADES TEÓRICAS
for(i in 1:K2) {
probs2[i] <- pweibull(cortes_s2[i+1], shape = shape_w2, scale = scale_w2) -
pweibull(cortes_s2[i], shape = shape_w2, scale = scale_w2)
}
probs2 <- probs2 / sum(probs2)
# 3. FRECUENCIAS OBSERVADAS Y ESPERADAS (Escaladas a 100)
n_base <- 100
Fo2 <- as.vector(table(cut(hum_s2, breaks = cortes_s2, right = FALSE))) * (n_base / n2)
Fe2 <- probs2 * n_base
# 4. ESTADÍSTICOS DEL TEST
chi2 <- sum((Fo2 - Fe2)^2 / Fe2)
gl2 <- K2 - 1 - 2
if(gl2 <= 0) gl2 <- 1
# Mantengo tu alfa de 0.99 según el código que me pasaste
crit2 <- qchisq(0.99, gl2)
res2 <- if(chi2 < crit2) "APROBADO" else "RECHAZADO"
pear2 <- cor(Fo2, Fe2) * 100
# 5. IMPRESIÓN (DISEÑO SIMPLIFICADO IGUAL AL ANTERIOR)
# \u00e1 = á | \u00f3 = ó
cat("Segmento 2 (Humedad Alta - Weibull):\n")## Segmento 2 (Humedad Alta - Weibull):
## Resultado Chi-cuadrado: APROBADO
## Chi-calc: 16,76 | Chi-crit: 20,09
## Correlación de Pearson: 93,49 %
# 1. CONFIGURACIÓN Y COLORES
col_bar1 <- "#AED6F1" # Azul claro
col_bar2 <- "#FAD7A0" # Naranja claro
col_line1 <- "blue4" # Azul oscuro
col_line2 <- "darkorange3" # Naranja oscuro
par(mar = c(6, 5, 4, 2))
# 2. CÁLCULO DE PROPORCIONES Y ANCHO
n_total_h <- length(hum_variable)
h_global_h <- hist(hum_variable, breaks = breaks_hum, plot = FALSE)
ancho_h <- h_global_h$breaks[2] - h_global_h$breaks[1] # Ancho de cada barra
# Convertimos las densidades a Porcentaje (%)
h_global_h$density <- (h_global_h$counts / n_total_h) * 100
# 3. DIBUJAR HISTOGRAMA GLOBAL (Eje Y en %)
colores_h <- ifelse(h_global_h$breaks[-1] <= 29.69, col_bar1, col_bar2)
# \u00e1=á | \u00ba=º | \u00ed=í | \u00f3=ó
plot(h_global_h, freq = FALSE, col = colores_h, border = "white",
main = "Gr\u00e1fica N\u00ba 7: Modelo H\u00edbrido de Humedad (%)",
xlab = "", ylab = "Frecuencia Relativa (%)",
axes = FALSE, ylim = c(0, max(h_global_h$density) * 1.2))
# 4. LÍNEA DIVISORIA
abline(v = 29.69, col = "gray40", lty = "dashed", lwd = 2)
# 5. DIBUJAR LAS CURVAS ESCALADAS A PORCENTAJE
# --- Curva 1: Weibull Reflejada (S1) ---
x_h1 <- seq(min_hum, 29.69, length.out = 200)
# Escalamos: Densidad * Ancho * 100 (para que coincida con el % de las barras)
y_h1 <- dweibull(29.69 - x_h1 + 0.01, shape = shape_s1, scale = scale_s1) * ancho_h * 100 * (length(hum_s1)/n_total_h)
lines(x_h1, y_h1, col = col_line1, lwd = 3)
# --- Curva 2: Weibull Directa (S2) ---
x_h2 <- seq(29.69, max_hum, length.out = 200)
y_h2 <- dweibull(x_h2, shape = shape_w2, scale = scale_w2) * ancho_h * 100 * (length(hum_s2)/n_total_h)
lines(x_h2, y_h2, col = col_line2, lwd = 3)
# 6. EJES Y DISEÑO
axis(2, las = 2, cex.axis = 0.7)
axis(1, at = round(breaks_hum, 2), labels = round(breaks_hum, 2), las = 2, cex.axis = 0.6)
grid(nx = NA, ny = NULL, col = "#D7DBDD", lty = "dotted")
# Etiqueta Eje X
mtext("Humedad (%)", side = 1, line = 4.5, cex = 0.9)
# Leyenda
legend("topright",
legend = c("S1: Weibull Reflejada", "S2: Weibull Directa"),
col = c(col_line1, col_line2),
lwd = 3, bty = "n", cex = 0.8)# 1. CARGAR LIBRERIAS
library(knitr)
# --- DATOS REALES OBTENIDOS (HUMEDAD) ---
# Segmento 1: Humedad Baja (Weibull Reflejado)
pear1 <- 99.99
chi1 <- 0.19
crit1 <- 7.81
res1 <- "APROBADO"
# Segmento 2: Humedad Alta (Weibull)
pear2 <- 93.49
chi2 <- 16.76
crit2 <- 20.09
res2 <- "APROBADO"
# --- GENERACION DE LA TABLA RESUMEN ---
# \u00e1 = á | \u00f3 = ó
resumen_final <- data.frame(
"Segmento" = c("S1: Humedad Baja (Weibull Ref.)",
"S2: Humedad Alta (Weibull)"),
"Pearson (%)" = c(pear1, pear2),
"Chi-Calc" = c(chi1, chi2),
"Chi-Crit" = c(crit1, crit2),
"Estado" = c(res1, res2)
)
# Imprimir tabla con formato kable
# \u00f3 = ó | \u00ed = í
kable(resumen_final,
format = "markdown",
align = "lcccc",
caption = "Tabla No. 2: Resumen de validaci\u00f3n de los modelos de probabilidad (Variable Humedad)")| Segmento | Pearson…. | Chi.Calc | Chi.Crit | Estado |
|---|---|---|---|---|
| S1: Humedad Baja (Weibull Ref.) | 99,99 | 0,19 | 7,81 | APROBADO |
| S2: Humedad Alta (Weibull) | 93,49 | 16,76 | 20,09 | APROBADO |
# 1. PREPARACIÓN DE PESOS Y PARÁMETROS
# Sincronizamos con los datos de humedad
n_total_h <- length(hum_variable)
prop_s1 <- length(hum_s1) / n_total_h
prop_s2 <- length(hum_s2) / n_total_h
# Colores del diseño solicitado
color_hibrido <- "#2C3E50" # Gris oscuro para el modelo
color_q1 <- rgb(0.16, 0.71, 0.39, 0.5) # Verde (25% - 35%)
color_q2 <- rgb(0.9, 0.29, 0.23, 0.5) # Rojo (> 40%)
# Calculamos el techo para la gráfica
# Usamos densidad para que las áreas de probabilidad sean correctas
h_dummy <- hist(hum_variable, breaks = breaks_hum, plot = FALSE)
max_y_h <- max(h_dummy$density) * 1.5
# 2. CREACIÓN DEL LIENZO PARA EL MODELO
par(mar = c(6, 5, 4, 2))
plot(1, type = "n",
main = "Gr\u00e1fica N\u00ba 8: \u00c1reas de Probabilidad (Modelo de Humedad)",
xlab = "Humedad (%)", ylab = "Densidad de Probabilidad",
xlim = range(breaks_hum),
ylim = c(0, max_y_h),
axes = FALSE)
# EJES Y CUADRÍCULA
axis(2, las = 2, cex.axis = 0.8)
axis(1, at = round(breaks_hum, 2), labels = round(breaks_hum, 2), las = 2, cex.axis = 0.7)
grid(nx = NA, ny = NULL, col = "#EBEDEF", lty = "dotted")
# 3. DIBUJAR LAS ÁREAS DE SOLUCIÓN (Sombreado)
# --- Pregunta 1: Humedad Moderada (25% a 35%) ---
# Parte A: Desde 25 hasta el corte (29.69) con Weibull Reflejada
x_q1_a <- seq(25, 29.69, length.out = 100)
y_q1_a <- dweibull(29.69 - x_q1_a + 0.01, shape_s1, scale_s1) * prop_s1
polygon(c(25, x_q1_a, 29.69), c(0, y_q1_a, 0), col = color_q1, border = NA)
# Parte B: Desde el corte (29.69) hasta 35 con Weibull Directa
x_q1_b <- seq(29.69, 35, length.out = 100)
y_q1_b <- dweibull(x_q1_b, shape_w2, scale_w2) * prop_s2
polygon(c(29.69, x_q1_b, 35), c(0, y_q1_b, 0), col = color_q1, border = NA)
# --- Pregunta 2: Humedad Crítica (> 40%) ---
# Usamos el modelo Weibull Directo del Segmento 2
x_q2 <- seq(40, max(breaks_hum), length.out = 100)
y_q2 <- dweibull(x_q2, shape_w2, scale_w2) * prop_s2
polygon(c(40, x_q2, max(breaks_hum)), c(0, y_q2, 0), col = color_q2, border = NA)
# 4. SUPERPOSICIÓN DEL MODELO HÍBRIDO (Línea Maestra)
# S1: Weibull Reflejada
curve(dweibull(29.69 - x + 0.01, shape_s1, scale_s1) * prop_s1,
from = min(breaks_hum), to = 29.69,
col = color_hibrido, lwd = 4, add = TRUE)
# S2: Weibull Directa
curve(dweibull(x, shape_w2, scale_w2) * prop_s2,
from = 29.69, to = max(breaks_hum),
col = color_hibrido, lwd = 4, add = TRUE)
# 5. LÍNEA DIVISORIA DE SEGMENTOS (Sutil)
abline(v = 29.69, col = "#BDC3C7", lty = "dashed", lwd = 1.5)
# 6. LEYENDA TÉCNICA
legend("topright",
legend = c("Modelo H\u00edbrido Unificado",
"S1: Moderada (25% - 35%)",
"S2: Cr\u00edtica (> 40%)"),
fill = c(NA, color_q1, color_q2),
border = c(NA, "white", "white"),
col = c(color_hibrido, NA, NA),
lty = c(1, NA, NA), lwd = c(4, NA, NA),
bty = "n", cex = 0.8)# 1. CARGAR LIBRERIAS (SILENCIADO)
# Usamos suppressPackageStartupMessages para ocultar los avisos de 'masked objects'
suppressPackageStartupMessages({
library(gt)
library(dplyr)
library(MASS)
})
# 2. CALCULO DE ESTADISTICOS ARITMETICOS (SOBRE LA VARIABLE HUMEDAD)
x_bar_h <- mean(hum_variable)
sigma_h <- sd(hum_variable)
n_h <- length(hum_variable)
# 3. CALCULO DEL ERROR ESTANDAR Y MARGEN AL 95%
error_est_h <- sigma_h / sqrt(n_h)
margen_error_h <- 2 * error_est_h
# 4. INTERVALO DE CONFIANZA
lim_inf_h <- x_bar_h - margen_error_h
lim_sup_h <- x_bar_h + margen_error_h
# 5. CONSTRUCCION DE LA TABLA RESUMEN
tabla_tlc_h <- data.frame(
Parametro = "Humedad Promedio (%)",
Lim_Inferior = lim_inf_h,
Media_Muestral = x_bar_h,
Lim_Superior = lim_sup_h,
Error_Estandar = paste0("+/- ", sprintf("%.4f", margen_error_h)),
Confianza = "95% (2*E)"
)
# 6. GENERACION DE LA TABLA VISUAL
tabla_tlc_h %>%
gt() %>%
tab_header(
title = md("**ESTIMACI\u00d3N DE LA MEDIA POBLACIONAL**"),
subtitle = "Aplicaci\u00f3n del Teorema del L\u00edmite Central (Humedad)"
) %>%
cols_label(
Parametro = "Par\u00e1metro",
Lim_Inferior = "L\u00edmite Inferior",
Media_Muestral = "Media Calculada",
Lim_Superior = "L\u00edmite Superior",
Error_Estandar = "Error Estimado"
) %>%
fmt_number(
columns = c(Lim_Inferior, Media_Muestral, Lim_Superior),
decimals = 4
) %>%
tab_style(
style = list(cell_fill(color = "#EBF5FB"), cell_text(color = "#1A5276", weight = "bold")),
locations = cells_body(columns = Media_Muestral)
)| ESTIMACIÓN DE LA MEDIA POBLACIONAL | |||||
| Aplicación del Teorema del Límite Central (Humedad) | |||||
| Parámetro | Límite Inferior | Media Calculada | Límite Superior | Error Estimado | Confianza |
|---|---|---|---|---|---|
| Humedad Promedio (%) | 66.8023 | 66.8982 | 66.9941 | +/- 0.0959 | 95% (2*E) |