8

我正在寻找类似“msm”包的东西,但是对于离散的马尔可夫链。例如,如果我有一个这样定义的转换矩阵

Pi <- matrix(c(1/3,1/3,1/3,
0,2/3,1/6,
2/3,0,1/2))

对于状态 A、B、C。如何根据该转换矩阵模拟马尔可夫链?

4

3 回答 3

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
于 2010-06-28T14:46:19.680 回答
6

,当我为你写它的时候,你找到了解决方案。这是我想出的一个简单示例:

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,它应该这样做。我的例子有一个稍微改变的概率转移矩阵,它遵守这个规则。

于 2010-05-02T19:33:51.343 回答
6

您现在可以使用markovchainCRAN 中提供的包。用户手册。很好,有几个例子。

于 2016-01-26T19:49:30.400 回答