title: Markov Chain previous states
body: <p>I've simulated a 1000 steps in a markov chain were there are in total 6 different states(0-5) and we started in state 5. With the bar plot we can we see how many times we are in each state. </p>
  
  <p>However, what i want to know is how many times we went to state 5, when the step just before it was from state 1. Since we are in total 26 times in state 1, the answer would the most be 26. Is there a way to see how many times we were in state 1 prior to going to state 5?</p>
  
  <pre><code>spec_sim &lt;- function(x){ 
    u &lt;- runif(1) 
      if(x==0){ 
        if(u &lt; 0.5){ 
          y &lt;- 3 
        } else { 
          y &lt;- 5 
        } 
      } else if(x==1){ 
        if(u&lt;0.1){ 
          y &lt;- 0 
        } else if(u &lt; 0.1 + 0.1){ 
              y &lt;- 1
        } else if(u &lt; 0.1 + 0.1 + 0.4){
              y &lt;- 3
        } else {
          y &lt;- 5}
  
      } else if(x==2){
          if(u&lt;0.2){
              y &lt;- 1
          } else if(u &lt; 0.2 + 0.2){
              y &lt;- 2
          } else if(u &lt; 0.2 + 0.2 + 0.3){
              y &lt;- 3
          } else {
              y &lt;- 5
          } 
      } else if(x==3){
          if(u&lt;0.3){
            y &lt;- 2
          } else if(u &lt; 0.3 + 0.5){
            y &lt;- 3
          } else{
            y &lt;- 5
          }
      } else if(x==4){
          if(u&lt;0.4){
            y &lt;- 3
          } else {
            y &lt;- 4
          }
      } else if(x==5){
          if(u&lt;0.4){
            y &lt;- 4
          } else {
            y &lt;- 5
          }
      }
    return(y)
  }
  
  set.seed(1) 
  results &lt;- numeric(1001)
  for(i in 2:length(results)){
      results[i]&lt;- spec_sim(results[i - 1]) 
  }
  
  results &lt;- results[-1]
  
  barplot(table(results), xlab="states", ylab="frequency", 
      main="1000 simuleringar av en Markovkedja")
  
  table(results)
  </code></pre>
  
  <p>Thank you for putting time into my question.</p>