1

The following source code is from a book. Comments are written by me to understand the code better.

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

I have a few confusions regarding this source code.

Why is states <- 1:length(init) used to generate states? What if states are like S ={-1, 0, 1, 2,...}?

user366312
  • 16,949
  • 65
  • 235
  • 452

1 Answers1

1

The exact labels of S is represented by the input labels.

States serves as the indices and in the very last line, simlist which are states from 1 to length(init) are used as indices to extract the correct labels.

Siong Thye Goh
  • 3,518
  • 10
  • 23
  • 31