title: R: Correctly Using the Break Statement
body: <p>I am working with the R programming language.</p>
  <p>I am trying to adapt the answer provided over here (<a href="https://stackoverflow.com/questions/55828125/manual-simulation-of-markov-chain-in-r">Manual simulation of Markov Chain in R</a>). The code below simulates some random numbers based on some user specified probabilities:</p>
  <pre><code>alpha &lt;- c(0,1,0,0, 0)
  mat &lt;- matrix(c(1,0,0,0,0,0.2,0.2,0.5,0.05,0.05, 0.3, 0.1,0.1,0.2,0.3, 0.2, 0.2, 0.2, 0.2, 0.2, 0,0,0,0,1), nrow = 5, ncol = 5, byrow = TRUE) 
  
  chainSim &lt;- function(alpha, mat, n) {
    out &lt;- numeric(n)
    out[1] &lt;- sample(1:5, 1, prob = alpha)
    for(i in 2:n) 
      out[i] &lt;- sample(1:5, 1, prob = mat[out[i - 1], ])
    out
  }
  </code></pre>
  <p>When we run this function, we can see examples of these random numbers (here, we specify the function to generate 6 random numbers):</p>
  <pre><code>chainSim(alpha, mat, 6)
  [1] 2 3 1 1 1 1
  </code></pre>
  <p>I want to adapt this code so that when the first &quot;1&quot; or &quot;5&quot; is encountered, the sequence stops. I tried to do this as follows (using the WHILE and BREAK commands):</p>
  <pre><code>alpha &lt;- c(0,1,0,0, 0)
  mat &lt;- matrix(c(1,0,0,0,0,0.2,0.2,0.5,0.05,0.05, 0.3, 0.1,0.1,0.2,0.3, 0.2, 0.2, 0.2, 0.2, 0.2, 0,0,0,0,1), nrow = 5, ncol = 5, byrow = TRUE) 
  
  chainSim &lt;- function(alpha, mat, n) {
      out &lt;- numeric(n)
      out[1] &lt;- sample(1:5, 1, prob = alpha)
      for(i in 2:n) {
          repeat{
              out[i] &lt;- sample(1:5, 1, prob = mat[out[i - 1], ])
              out
              if (1 %in% out[i] || 5 %in% out[i] ) break
          }
      }}
  
  # simulate numbers until first 1 or 5 is encountered : does not work
  chainSim(alpha, mat, n)
  
  # repeat chainSim 100 times : does not work (&quot;sim_final&quot; will have likely have an uneven number of entries in each row)
  
  sim &lt;- replicate(chainSim(alpha, mat, n), n = 100)
  sim_final = data.frame(t(sim))
  </code></pre>
  <p>But when I tried to do this, chainSim() does not produce any random numbers and &quot;sim&quot; produces 100 NULL's.</p>
  <p><strong>Can someone please show me how to fix this?</strong></p>
  <p>Thanks!</p>