title: switch statement help in R
body: <p>I've got the following code in R:</p>
  
  <pre><code>func.time &lt;- function(n){
  times &lt;- c()
  for(i in 1:n){
  
  r &lt;- 1 #x is the room the mouse is in
  X &lt;- 0 #time, starting at 0
  while(r != 5){
  
  if(r == 1){
      r &lt;- sample(c(2,3),1) }
  
  else if(r == 2){
      r &lt;- sample(c(1,3), 1) }
  
  else if(r == 3){
      r &lt;- sample(c(1,2,4,5), 1) }
  
  else if (r == 4){
      r &lt;- sample(c(3,5), 1) }
  
   X &lt;- X + 1
   }
  
   times &lt;- c(X, times)
   }
   mean(times)
   }
   func.time(10000)
  </code></pre>
  
  <p>It works fine, but I've been told that using switch() can speed it up seeing as I've got so many if else statements but I can't seem to get it to work, any help is appreciated in advance.</p>
  
  <p><strong>Edit</strong>
  I've tried this:</p>
  
  <pre><code>func.time &lt;- function(n) {
      times &lt;- c() 
      for(i in 1:n) {
          r &lt;- 1 #x is the room the mouse is in 
          X &lt;- 0 #time, starting at 0 
          while(r != 5) { 
              switch(r, "1" = sample(c(2,3), 1),
                           "2" = sample(c(1,3), 1),
                           "3" = sample(c(1,2,4,5), 1),
                           "4" = sample(c(3,5))) 
              X &lt;- X + 1 
          } 
          times &lt;- c(X, times) 
      } 
      mean(times) 
  } 
  
  func.time(10000)
  </code></pre>
  
  <p>But it was a basic attempt, I'm not sure I've understood the switch() method properly.</p>