R中的简单马尔可夫链(可视化) [英] Simple Markov Chain in R (visualization)

查看:38
本文介绍了R中的简单马尔可夫链(可视化)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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...).

谢谢.

推荐答案

这显示了如何将随机转移矩阵应用于特定的起始向量:c(1,0,0,0):

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:

这篇关于R中的简单马尔可夫链(可视化)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆