2011-11-06 218 views
12

我想在R中做一个简单的一阶马尔可夫链。我知道有像MCMC这样的软件包,但找不到能以图形方式显示的软件包。这甚至有可能吗?如果给定一个转换矩阵和一个初始状态,可以很好地看到马尔可夫链中的路径(也许我必须手动完成这个操作)。R中的简单马尔可夫链(可视化)

谢谢。

+0

我不熟悉这方面的包,但如果你不能找到你喜欢的罐头绘图命令,你总是可以自己提取矩阵和绘制出来:http://stackoverflow.com/questions/5453336/r-plot-correlation-matrix-into-a-graph –

+0

谢谢。这是另一个想法,如果没有这样的东西存在:)。 – user1028531

+0

稍微澄清一点或者你想要的东西的一个粗略例子会有帮助:下面的答案都在地图上,因为人们以不同的方式解释你的问题。 –

回答

10

这显示了如何将随机转换矩阵应用到特定的起始载体: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)))) 

你可以看到它达到平衡: enter image description here

+0

我得到'错误:意外'['in'[“ 执行停止 ' –

+0

我很抱歉听到这个消息。代码仍然运行正确的输出在R 3.1.2 –

+0

嗯......似乎在Rstudio中工作(虽然它也打印'错误:意外'['在'[“'),但不是当我执行它作为Rscript通过bash。你有什么想法,为什么? –

2

您可以使用markovchain R软件包,模拟离散时间马尔可夫链,并包含基于igraph软件包的绘图工具。

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)