title: Trying to increase efficiency of function that converts a data frame into a larger data frame using R
body: <p>I'm looking for an efficient way to turn a data frame like this:</p>
  
  <pre><code>1 45
  2 49
  5 25
  6 24
  9 32
  11 39
  </code></pre>
  
  <p>into a data frame like this:</p>
  
  <pre><code>1 45
  2 49
  3 49
  4 49
  5 25
  6 24
  7 24
  8 24
  9 32
  10 32
  11 39
  </code></pre>
  
  <p>So this is basically adding in rows for the missing values in the sequence in the left column and using the last previous value for the right column. I'm trying to do this for a data frame with 1,000,000 rows and my function is really slow. I assume there must be a quicker way.</p>
  
  <p>The way I do it is to first put it into a data.frame I call <code>w</code>:</p>
  
  <pre><code>1 45
  2 49
  3 0
  4 0
  5 25
  6 24
  7 0
  8 0
  9 32
  10 0
  11 39
  </code></pre>
  
  <p>That step is pretty quick and not an issue but then I use:</p>
  
  <pre><code>for (i in 1:nrow(w)) {
    if(w[i,2]==0) {w[i,2]&lt;-w[i-1,2]}
  }
  </code></pre>
  
  <p>Most the time is spent doing the '&lt;-' but I've tried many different ways and this is the quickest I can think of. It is quick when I do it for 20,000 rows but when I try on 1,000,000 rows it takes about 30 minutes. </p>
  
  <p>Does anyone have any ideas?</p>