set.seed(123) # Para reproducibilidad
n <- 100 # Número de semanas
rain_data <- data.frame(
week = 1:n,
rain = sample(c("0", "1-5", "6+"), n, replace = TRUE)
)ejemplo 2 markov
GENERACION DE LA BASE
GENERACION DE LA MATRIZ DE TRANSICION USANDO EL PAQUETE MARKOVCHAIN
library(markovchain)Warning: package 'markovchain' was built under R version 4.4.2
Cargando paquete requerido: Matrix
Package: markovchain
Version: 0.10.0
Date: 2024-11-14 00:00:02 UTC
BugReport: https://github.com/spedygiorgio/markovchain/issues
PE <- rain_data$rain
# Crear la matriz de transición
P1 <- createSequenceMatrix(PE)
print(P1) 0 1-5 6+
0 7 13 13
1-5 13 7 12
6+ 13 12 9
GENERANDO LAS PROBABILIDADES DE PASAR DE UN ESTADO AL OTRO.
fit <- markovchainFit(data = PE, confidencelevel = 0.95)
print(fit$estimate@transitionMatrix) 0 1-5 6+
0 0.2121212 0.3939394 0.3939394
1-5 0.4062500 0.2187500 0.3750000
6+ 0.3823529 0.3529412 0.2647059
HACIENDO LAS PREDICCIONES A PARTIR DE UN X0
# Estado actual
current_state <- "0"
# Número de pasos hacia adelante
n_steps <- 5
# Predicción del estado futuro
predictions <- predict(fit$estimate, newdata = current_state, n.ahead = n_steps)
print(predictions)[1] "1-5" "0" "6+" "0" "6+"
# Visualizar la matriz de transición
plot(fit$estimate)