【问题标题】:Understanding Markov Chain source code in R [duplicate]理解 R 中的马尔可夫链源代码 [重复]
【发布时间】:2019-05-09 22:41:12
【问题描述】:

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

#==================================================================
# 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


    【解决方案1】:

    S 的准确标签由输入标签表示。

    States 用作索引,在最后一行,simlist 是从 1 到 length(init) 的状态,用作提取正确标签的索引。

    【讨论】:

    • 这里为什么需要labels[simlist]
    • 在您提供的原始标签中表达事物。
    猜你喜欢
    • 2019-09-27
    • 2015-11-15
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-15
    相关资源
    最近更新 更多