title: R - Carry Forward Values
body: <p>Here's my starting dataset:</p>
  
  <pre><code>&gt; data
    ID Record Value
     A      1   100
     A      3   200
     A      4   300
     B      1   800
  </code></pre>
  
  <p>For each ID, I want a record for each number 1 through 4. If a record is not available, create it using the most recent record.</p>
  
  <p>The final dataset should look like this:</p>
  
  <pre><code>&gt; newdata
       ID Updt_Record Value
        A           1   100
        A           2   100
        A           3   200
        A           4   300
        B           1   800
        B           2   800
        B           3   800
        B           4   800
  </code></pre>
  
  <p>To do this, I am currently using <code>dplyr</code>:</p>
  
  <pre><code>library(dplyr)
  
  data1 &lt;- data %&gt;% group_by(ID) %&gt;% filter(Record &lt;= 1) %&gt;% filter(Record == max(Record)) %&gt;% mutate(Updt_Record = 1)
  data2 &lt;- data %&gt;% group_by(ID) %&gt;% filter(Record &lt;= 2) %&gt;% filter(Record == max(Record)) %&gt;% mutate(Updt_Record = 2)
  data3 &lt;- data %&gt;% group_by(ID) %&gt;% filter(Record &lt;= 3) %&gt;% filter(Record == max(Record)) %&gt;% mutate(Updt_Record = 3)
  data4 &lt;- data %&gt;% group_by(ID) %&gt;% filter(Record &lt;= 4) %&gt;% filter(Record == max(Record)) %&gt;% mutate(Updt_Record = 4)
  
  newdata &lt;- data1 %&gt;%
    bind_rows(data2) %&gt;% bind_rows(data3) %&gt;% bind_rows(data4) %&gt;%
    arrange(ID, Record) %&gt;%
    select(ID, Updt_Record, Value)
  </code></pre>
  
  <p>Is there a more efficient way of doing this? Thanks!</p>