title: Loops and variable scope in R
body: <p>I have following for loop in R: </p>
  
  <pre><code>v = c(1,2,3,4)
  s = create.some.complex.object()
  for (i in v){
     print(i)
     s = some.complex.function.that.updates.s(s)
  }
  # s here has the right content.
  </code></pre>
  
  <p>Needless to say, this loop is horribly slow in R.
  I tried to write it in functional style: </p>
  
  <pre><code>   lapply(v, function(i){
        print(i)
        s = some.complex.function.that.updates.s(s)
     })
     # s wasn't updated.
  </code></pre>
  
  <p>But this doesn't work, because <code>s</code> is passed by value and not by reference.
  I only need the result of the last iteration, not all of the intermediate steps.
  How do I formulate the first loop in R-style?</p>
  
  <p>Mulone</p>