title: speeding up a loop with loop-carried values in R
body: <p>I'm trying to speed up code that takes time series data and limits it to a maximum value and then stretches it forward until sum of original data and the "stretched" data are the same.</p>
  
  <p>I have a more complicated version of this that is taking 6 hours to run on 100k rows. I don't think this is vectorizable because it uses values calculated on prior rows - is that correct?</p>
  
  <pre><code>x &lt;- c(0,2101,3389,3200,1640,0,0,0,0,0,0,0)
  dat &lt;- data.frame(x=x,y=rep(0,length(x)))
  remainder &lt;- 0
  upperlimit &lt;- 2000
  for(i in 1:length(dat$x)){
    if(dat$x[i] &gt;= upperlimit){
      dat$y[i]  &lt;- upperlimit
    } else {
      dat$y[i] &lt;- min(remainder,upperlimit)
    }
    remainder  &lt;-  remainder + dat$x[i] - dat$y[i]
  }
  dat
  </code></pre>
  
  <p>I understand you can use <code>ifelse</code> but I don't think <code>cumsum</code> can be used to carry forward the remainder - <code>apply</code> doesn't help either as far as I know. Do I need to resort to <code>Rcpp</code>? Thank you greatly. </p>