我正在寻找类似'msm'包的东西,但是对于离散马尔可夫链。例如,如果我有一个定义为此类的转换矩阵
Pi <- matrix(c(1/3,1/3,1/3,
0,2/3,1/6,
2/3,0,1/2))
表示状态A,B,C。如何根据转移矩阵模拟马尔可夫链?
谢谢,
答案 0 :(得分:8)
前段时间我写了一组用于离散马尔可夫链概率矩阵的模拟和估计的函数:http://www.feferraz.net/files/lista/DTMC.R。
您要问的相关代码:
simula <- function(trans,N) {
transita <- function(char,trans) {
sample(colnames(trans),1,prob=trans[char,])
}
sim <- character(N)
sim[1] <- sample(colnames(trans),1)
for (i in 2:N) {
sim[i] <- transita(sim[i-1],trans)
}
sim
}
#example
#Obs: works for N >= 2 only. For higher order matrices just define an
#appropriate mattrans
mattrans <- matrix(c(0.97,0.03,0.01,0.99),ncol=2,byrow=TRUE)
colnames(mattrans) <- c('0','1')
row.names(mattrans) <- c('0','1')
instancia <- simula(mattrans,255) # simulates 255 steps in the process
答案 1 :(得分:6)
Argh ,你在我为你写的时候找到了解决方案。这是我想出的一个简单例子:
run = function()
{
# The probability transition matrix
trans = matrix(c(1/3,1/3,1/3,
0,2/3,1/3,
2/3,0,1/3), ncol=3, byrow=TRUE);
# The state that we're starting in
state = ceiling(3 * runif(1, 0, 1));
cat("Starting state:", state, "\n");
# Make twenty steps through the markov chain
for (i in 1:20)
{
p = 0;
u = runif(1, 0, 1);
cat("> Dist:", paste(round(c(trans[state,]), 2)), "\n");
cat("> Prob:", u, "\n");
newState = state;
for (j in 1:ncol(trans))
{
p = p + trans[state, j];
if (p >= u)
{
newState = j;
break;
}
}
cat("*", state, "->", newState, "\n");
state = newState;
}
}
run();
请注意,您的概率转换矩阵在每行中的总和不会达到1。我的例子有一个略微改变的概率转移矩阵,它符合这个规则。
答案 2 :(得分:5)
您现在可以使用CRAN中提供的markovchain
包。用户manual。非常好,有几个例子。