【问题标题】:Understanding Markov Chain source code in R理解 R 中的马尔可夫链源代码
【发布时间】:2019-09-27 10:03:03
【问题描述】:

以下源代码来自一本书。注释是我写的,以便更好地理解代码。

#==================================================================
# markov(init,mat,n,states) = Simulates n steps of a Markov chain 
#------------------------------------------------------------------
# init = initial distribution 
# mat = transition matrix 
# labels = a character vector of states used as label of data-frame; 
#           default is 1, .... k
#-------------------------------------------------------------------
markov <- function(init,mat,n,labels) 
{ 
    if (missing(labels)) # check if 'labels' argument is missing
    {
        labels <- 1:length(init) # obtain the length of init-vecor, and number them accordingly.
    }

    simlist <- numeric(n+1) # create an empty vector of 0's
    states <- 1:length(init)# ???? use the length of initial distribution to generate states.
    simlist[1] <- sample(states,1,prob=init) # sample function returns a random permutation of a vector.
                        # select one value from the 'states' based on 'init' probabilities.

    for (i in 2:(n+1))
    { 
        simlist[i] <- sample(states, 1, prob = mat[simlist[i-1],]) # simlist is a vector.
                                                    # so, it is selecting all the columns 
                                                    # of a specific row from 'mat'
    }

    labels[simlist]
}
#==================================================================

我对此源代码有一些困惑。

为什么使用states &lt;- 1:length(init) 来生成状态?如果状态像 S ={-1, 0, 1, 2,...} 会怎样?

【问题讨论】:

    标签: r statistics probability markov-chains markov


    【解决方案1】:

    州的名称并不需要具有任何统计意义,只要它们不同即可。因此,在模拟状态之间的转换时,为它们选择 states &lt;- 1:length(init) 或任何其他名称是非常好的。但最终,出于实际目的,我们经常会想到一些标签,例如 -1、0、...、n,如您的示例所示。您可以将这些名称作为labels 参数提供,然后labels[simlist] 将逐个元素地将1:length(init) 重命名为labels。即,如果最初我们有c(1, 2, 3),而您将labels 提供为c(5, 10, 12),那么输出将是后一个向量。例如,

    (states <- sample(1:3, 10, replace = TRUE))
    # [1] 1 3 3 2 2 1 2 1 3 3
    labels <- c(5, 10, 12)
    labels[states]
    # [1]  5 12 12 10 10  5 10  5 12 12
    

    【讨论】:

    • 州名只要不同就没有统计意义。 - 如果我们需要计算期望值怎么办?
    • @user366312,是的,你是对的,名字可以是有意义的,虽然我想补充一点,在做一些像计算期望值这样的事情之前应该考虑一下。例如,如果只有两个状态,0 和 1,那么像 0.65 这样的期望值是一个有意义的数字吗?不管这个好点是什么,我的帖子的其余部分都回答了您问题的技术部分。特别是,即使这些名称对某些后续分析很重要,但它们对模拟部分并不重要,因此可以使用1:length(init)
    • 这里为什么需要labels[simlist]
    • @user366312,仅适用于我在回答中提到的内容。您可以将模拟结果返回为 simlist,在这种情况下,状态将命名为 1:length(init)。现在要使用labels 提供的名称,我们需要labels[simlist],它的工作原理与我的答案中的示例一样。即,状态 1 现在将重命名为 labels[1],状态 2 将重命名为 labels[2],等等。
    猜你喜欢
    • 1970-01-01
    • 2015-11-15
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    相关资源
    最近更新 更多