# UNIVERSIDAD NACIONAL DEL ALTIPLANO
# INGENIERIA ESTADISTICA E INFORMATICA 
# ESTADISTICA BAYESIANA
# TEMA: CADENA DE MARKOV Y MATRIX DE TRANSICION
library(markovchain)
## Warning: package 'markovchain' was built under R version 4.0.5
## Package:  markovchain
## Version:  0.8.6
## Date:     2021-05-17
## BugReport: https://github.com/spedygiorgio/markovchain/issues
library(DBI)
## Warning: package 'DBI' was built under R version 4.0.5
library(Rcpp)
## Warning: package 'Rcpp' was built under R version 4.0.5
# Matriz de Transicion
EstadosClima <- c("Soleado", "Nublado", "Lluvia")
byRow <- TRUE
EstadosClimaMatrix <- matrix(data = c(0.70, 0.2, 0.1,
                                 0.3, 0.4, 0.3,
                                 0.2, 0.45, 0.35), byrow = byRow, nrow = 3,
                        dimnames = list(EstadosClima, EstadosClima))

# Matriz de Transicion con markovchain
mcClima <- new("markovchain", states = EstadosClima, byrow = byRow,
                 transitionMatrix = EstadosClimaMatrix, name = "Clima")
# Resumen de la Cadena
summary(mcClima)
## Clima  Markov chain that is composed by: 
## Closed classes: 
## Soleado Nublado Lluvia 
## Recurrent classes: 
## {Soleado,Nublado,Lluvia}
## Transient classes: 
## NONE 
## The Markov chain is irreducible 
## The absorbing states are: NONE
# Dibujamos la Cadena
plot(mcClima, main = "Cadena de Markov")

# Otras Funciones importantes que nos ayuda clasificar el tipo de cadena
absorbingStates(mcClima)
## character(0)
transientStates(mcClima)
## character(0)
recurrentClasses(mcClima)
## [[1]]
## [1] "Soleado" "Nublado" "Lluvia"
# Analisis Probabilistico
transitionProbability(object = mcClima, t0 = "Soleado", t1= "Lluvia")
## [1] 0.1
mcClima[2,3]
## [1] 0.3
# Matriz de Transicion en n pasos
n=4
mcClima^n
## Clima^4 
##  A  3 - dimensional discrete Markov Chain defined by the following states: 
##  Soleado, Nublado, Lluvia 
##  The transition matrix  (by rows)  is defined as follows: 
##           Soleado   Nublado    Lluvia
## Soleado 0.4851750 0.3074125 0.2074125
## Nublado 0.4487250 0.3256375 0.2256375
## Lluvia  0.4396125 0.3301938 0.2301938
# La Cadena en n pasos en adelante
x0 <- c(0.2,0.3,0.1)
n=4
xn <- x0*(mcClima^n)
xn
##        Soleado   Nublado    Lluvia
## [1,] 0.2756137 0.1921931 0.1321931
sum(xn) # Suma de Probabilidades
## [1] 0.6
# La Ditribucion Estacionaria
DistEst <- steadyStates(mcClima)
DistEst
##        Soleado   Nublado    Lluvia
## [1,] 0.4636364 0.3181818 0.2181818