title: Avoiding a loop when entry i might take the value of entry i-1
body: <p>I have vectors with mostly <code>NA</code> entries. I want to replace every <code>NA</code> with that vector's preceding non-<code>NA</code> entry. Specifically, the first entry will always be a 1, followed by a bunch of <code>NA</code>s, which I want to replace with 1. The <code>i</code>th entry could be another numeric, let's say 2, followed by more <code>NA</code>s that I want to replace with 2. And so on. The loop below achieves this, but there has to be a more R way to do it, right? I wanted to vectorize with <code>ifelse()</code>, but I couldn't figure out how to replace the <code>i</code>th entry with the <code>i-1</code>th entry.</p>
  
  <pre><code>&gt; vec &lt;- rep(NA, 10)
  &gt; vec
   [1] NA NA NA NA NA NA NA NA NA NA
  &gt; vec[1] &lt;- 1; vec[4] &lt;- 2; vec[7] &lt;- 3
  &gt; vec
   [1]  1 NA NA  2 NA NA  3 NA NA NA
  &gt; for (i in 1:length(vec)) if (is.na(vec[i])) vec[i] &lt;- vec[i-1]
  &gt; vec
   [1] 1 1 1 2 2 2 3 3 3 3
  </code></pre>
  
  <p>Thanks! </p>
  
  <p>If context helps, I am adjusting for stock splits from the WRDS database, which has a column that shows when and how a split occurs.</p>