title: Output for a nested function in r
body: <p>The code below is one way to model "Snakes and ladders" game:</p>
  
  <pre><code>    ladder.df &lt;- data.frame(start=c(1,4,9,21,28,36,51,71,80), end=c(38,14,31,42,84,44,67,91,100))
  snake.df &lt;- data.frame(start=c(98,95,93,87,64,62,56,49,47,16), end=c(78,75,73,24,60,19,53,11,26,6))
  
  game&lt;-function(nop){
  positions&lt;-c()
  curpos &lt;- 0 # Current location
  nroll &lt;- 0 # Number of rolls
  snakes &lt;- 0 # Number of snakes encountered
  ladders &lt;- 0 # Number of ladders encountered
  players&lt;-c(1:nop)
  ladders2&lt;-c()
  snakes2&lt;-c()
  
  for(i in 1:nop){
  while(curpos &lt; 100) {
    roll &lt;- sample(6,1) 
    curpos &lt;- curpos + roll 
    nroll &lt;- nroll + 1 
    positions&lt;-append(positions,curpos)
  
    # Need to check if we landed on a ladder or slide and move forward or back
    if (any(ladder.df$s %in% curpos)) {
      curpos &lt;- ladder.df$e[ladder.df$s %in% curpos]
      ladders &lt;- ladders + 1
    }
    if (any(snake.df$s %in% curpos)) {
      curpos &lt;- snake.df$e[slide.df$s %in% curpos]
      snakes &lt;- snakes + 1 
    }
  }
  data&lt;-data.frame("Player:"=players[i],"Ladders"=ladders,"Snakes"=snakes,"Number of rolls"=nroll)
  print(data)
  }
  }
  </code></pre>
  
  <p>The code runs fine, however, the output I want ( that is, no. of ladders, snakes and number of throws for <strong>each</strong> player) duplicates the results of the last player, since neither snakes, ladders or no. of throws dependent on i. Question is- how do I fix this? I tried various approaches (like assigning all the 'snakes' values to the vector and call a certain value from a vector, corresponding to the value i) but it will not budge. Thanks for all the support in advance!</p>