user1028531
user1028531

Reputation: 129

Simple Markov Chain in R (visualization)

i'd like to do a simple first order markov chain in R. I know there are packages like MCMC, but couldn't found one to display it graphically. Is this even possible? It would be nice if given a transition matrix and an initial state, one can visually see the path through the markov chain (maybe i've to do this by hand...).

Thanks.

Upvotes: 12

Views: 7595

Answers (4)

Giorgio Spedicato
Giorgio Spedicato

Reputation: 2503

You can use markovchain R package, that models Discrete Time Markov Chains and contains a plotting facility based on igraph package.

library(markovchain) #loading the package
myMatr<-matrix(c(0,.2,.8,.1,.8,.1,.3,0,.7),byrow=TRUE,nrow = 3) #defining a transition matrix
rownames(myMatr)<-colnames(myMatr)<-c("a","b","c")
myMc<-as(myMatr, "markovchain")
plot(myMc)

Upvotes: 3

IRTFM
IRTFM

Reputation: 263301

This shows how to apply a random transition matrix to a particular starting vector: c(1,0,0,0):

set.seed(123)
tmat <- matrix(rnorm(16)^2,ncol=4) 
   # need entries to be positive, could have used abs()
tmat <- tmat/rowSums(tmat) # need the rows to sum to 1
tmat
            [,1]       [,2]       [,3]        [,4]
[1,] 0.326123580 0.01735335 0.48977444 0.166748625
[2,] 0.016529424 0.91768404 0.06196453 0.003822008
[3,] 0.546050789 0.04774713 0.33676288 0.069439199
[4,] 0.001008839 0.32476060 0.02627217 0.647958394
require(expm)   # for the %^% function
matplot( t(         # need to transpose to get arguments to matplot correctly
       sapply(1:20, function(x) matrix(c(1,0,0,0), ncol=4) %*% (tmat %^% x) ) ) )

You can see it approaching equilibrium: enter image description here

Upvotes: 10

Jake
Jake

Reputation: 283

The package coda (http://cran.r-project.org/web/packages/coda/index.html) has tools for analyzing MCMC results, including some plotting functionality.

Upvotes: 4

Itamar
Itamar

Reputation: 2141

Perhaps this query on Biostar can help you: Visualizing HMM files of HMMER3. It point to two external applications, LogoMat-M and HMMeditor, for visualizing Profile Hidden Markov Models (pHMMs).

Upvotes: 2

Related Questions