Search code examples
rsimulationmontecarlo

R:Montecarlo simulation using transition matrix


I have a transition matrix :

a
           A          B         C     D         E          F          G          H         I
A 0.00000000 0.66666667 0.0000000 0.000 0.0000000 0.00000000 0.00000000 0.33333333 0.0000000
B 0.08823529 0.02941176 0.2941176 0.000 0.2352941 0.05882353 0.02941176 0.11764706 0.1470588
C 0.00000000 0.37500000 0.0000000 0.000 0.4166667 0.00000000 0.00000000 0.08333333 0.1250000
D 0.00000000 0.00000000 0.3333333 0.000 0.0000000 0.00000000 0.33333333 0.33333333 0.0000000
E 0.00000000 0.50000000 0.2307692 0.000 0.0000000 0.00000000 0.00000000 0.07692308 0.1923077
F 0.00000000 0.00000000 0.0000000 0.000 0.5000000 0.00000000 0.00000000 0.00000000 0.5000000
G 0.00000000 0.50000000 0.0000000 0.500 0.0000000 0.00000000 0.00000000 0.00000000 0.0000000
H 0.00000000 0.27272727 0.3636364 0.000 0.1818182 0.00000000 0.00000000 0.00000000 0.1818182
I 0.00000000 0.31250000 0.1875000 0.125 0.3125000 0.00000000 0.00000000 0.06250000 0.0000000

and i have in my dataset a categorical variable :

state=c("G" ,"I" ,"G", "C", "D", "I","A" ,"G", "G" ,"H", "C", "D" ,"C", "H" "F", "B", "F" ,"G" ,"D", "E" ,"B" ,"H" ,"E" ,"C" ,"F" ,"H", "C", "H" ,"F" ,"H") 

and now i want to use my transition matrix to simulate a variable just like my variable state using the Monte carlo approach. Can you advise me which R package or function can help me to do my simulation please !


Solution

  • You could use markovchainSequence from package markovchain. Example:

    mat <- as.matrix(read.table(text="
    0.00000000 0.66666667 0.0000000 0.000 0.0000000 0.00000000 0.00000000 0.33333333 0.0000000
    0.08823529 0.02941176 0.2941176 0.000 0.2352941 0.05882353 0.02941176 0.11764706 0.1470588
    0.00000000 0.37500000 0.0000000 0.000 0.4166667 0.00000000 0.00000000 0.08333333 0.1250000
    0.00000000 0.00000000 0.3333333 0.000 0.0000000 0.00000000 0.33333333 0.33333333 0.0000000
    0.00000000 0.50000000 0.2307692 0.000 0.0000000 0.00000000 0.00000000 0.07692308 0.1923077
    0.00000000 0.00000000 0.0000000 0.000 0.5000000 0.00000000 0.00000000 0.00000000 0.5000000
    0.00000000 0.50000000 0.0000000 0.500 0.0000000 0.00000000 0.00000000 0.00000000 0.0000000
    0.00000000 0.27272727 0.3636364 0.000 0.1818182 0.00000000 0.00000000 0.00000000 0.1818182
    0.00000000 0.31250000 0.1875000 0.125 0.3125000 0.00000000 0.00000000 0.06250000 0.000000",
               header=FALSE,stringsAsFactors = FALSE))
    rownames(mat) <- colnames(mat) <- LETTERS[1:9]
    mat[,9] <- 1-rowSums(mat[,1:8]) #To make sure your rows sum to 1
    
    statesNames <- LETTERS[1:9]
    markovchain_object <- new("markovchain", states = statesNames, transitionMatrix = mat)
    
    markovchainSequence(n=10, markovchain = markovchain_object)
    
     [1] "C" "H" "C" "E" "C" "B" "C" "E" "B" "G"