模拟R中的马尔可夫链和序列搜索

时间:2017-11-23 01:03:19

标签: r probability markov-chains

所以我正在研究用R模拟马尔可夫链,其中状态是晴天(S),阴天(C)和下雨(R),我正在寻找一个阳光灿烂的日子跟随两个连续的概率阴天。

这是我到目前为止所做的:

    P = matrix(c(0.7, 0.3, 0.2, 0.2, 0.5, 0.6, 0.1, 0.2, 0.2), 3)
    print(P)
    x = c("S", "C", "R") 
    n = 10000
    states = character(n+100)
    states[1] = "C"

    for (i in 2:(n+100)){
    if (states[i-1] == "S") {cond.prob = P[1,]}
    else if (states[i-1] == "C") {cond.prob = P[2,]}
    else {cond.prob = P[3,]}
    states[i]=sample(x, 1, prob = cond.prob )
    }

    print(states[1:100])
    states = states[-(1:100)]  
    head(states)
    tail(states)
    states[1:200]

最后,我留下了一系列状态。我希望将这个序列分成三个状态的组(对于链中的三天),然后计算那些等于SCC的三个设置状态的数量。

关于如何做到这一点,我正在做一个空白,我们将非常感谢任何帮助!!

2 个答案:

答案 0 :(得分:1)

假设您想要一个滑动窗口(即SCC可能出现在1-3或2-4等位置),将状态折叠为字符串和正则表达式搜索应该可以解决问题:

collapsed <- paste(states, collapse="")
length(gregexpr("SCC", collapsed)[[1]])

另一方面,如果你不想要一个滑动窗口(即,SCC必须在1-3位,或4-6,或7-9等),那么你可以使用tapply

indexer <- rep(1:(ceiling(length(states)/3)), each=3, length=length(states))
chopped <- tapply(states, indexer, paste0, collapse="")
sum(chopped == "SCC")

答案 1 :(得分:1)

Eric提供了正确答案,但仅仅是为了完整性: 你可以使用链的均衡分布得到你正在寻找的概率:

# the equilibrium distribution
e <- eigen(t(P))$vectors[,1]
e.norm <- e/sum(e)
# probability of SCC
e.norm[1] * P[1,2] * P[2,2]

计算成本较低,可以更准确地估计概率,因为您的模拟会偏向链的初始状态。