理解R中的马尔可夫链源代码

理解R中的马尔可夫链源代码,r,R,以下源代码来自一本书。我写评论是为了更好地理解代码 #================================================================== # markov(init,mat,n,states) = Simulates n steps of a Markov chain #------------------------------------------------------------------ # init = initial dist

以下源代码来自一本书。我写评论是为了更好地理解代码

#==================================================================
# 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]
}
#==================================================================
#==================================================================
#马尔可夫(init,mat,n,states)=模拟马尔可夫链的n个步骤
#------------------------------------------------------------------
#init=初始分布
#mat=转移矩阵
#标签=用作数据帧标签的状态的字符向量;
#默认值为1。。。。K
#-------------------------------------------------------------------

markovS的确切标签由输入标签表示


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

为什么这里需要
labels[simlist]
来用您提供的原始标签表示内容。