title: Widen R dataframe
body: <p>I am trying to widen a dataframe in R but it seems like in a way that is unusual as I haven't been able find a simple way to do so after lots of searching here.</p>
  <p>Say I have a dataframe like this, where the ID is a number that identifies a unique person and this unique person might have several codes associated with them:</p>
  <pre><code>ID&lt;-c(1, 2, 2, 2, 3, 3,4)
  CODE&lt;-c(123, 938, 293, 456, 203, 203, 91)
  df &lt;- data.frame(ID, CODE)
  </code></pre>
  <p>I want to widen it so that there is only one row per ID and the codes are added to additional columns.  This should result in as many new columns being generated as there are codes for the ID that has the most number of codes associated with it.  If an ID only has one code, for example, then all newly generated columns after the first should be filled with NAs.  The resulting dataframe should look like this:</p>
  <div class="s-table-container">
  <table class="s-table">
  <thead>
  <tr>
  <th>ID</th>
  <th>CODE1</th>
  <th>CODE2</th>
  <th>CODE3</th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td>1</td>
  <td>123</td>
  <td>NA</td>
  <td>NA</td>
  </tr>
  <tr>
  <td>2</td>
  <td>938</td>
  <td>293</td>
  <td>456</td>
  </tr>
  <tr>
  <td>3</td>
  <td>203</td>
  <td>203</td>
  <td>NA</td>
  </tr>
  <tr>
  <td>4</td>
  <td>91</td>
  <td>NA</td>
  <td>NA</td>
  </tr>
  </tbody>
  </table>
  </div>
  <p>It would be even better if duplicate codes could be removed as well so that the result would actually be like this (such that the second occurrence of 203 for ID 3 becomes an NA):</p>
  <div class="s-table-container">
  <table class="s-table">
  <thead>
  <tr>
  <th>ID</th>
  <th>CODE1</th>
  <th>CODE2</th>
  <th>CODE3</th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td>1</td>
  <td>123</td>
  <td>NA</td>
  <td>NA</td>
  </tr>
  <tr>
  <td>2</td>
  <td>938</td>
  <td>293</td>
  <td>456</td>
  </tr>
  <tr>
  <td>3</td>
  <td>203</td>
  <td>NA</td>
  <td>NA</td>
  </tr>
  <tr>
  <td>4</td>
  <td>91</td>
  <td>NA</td>
  <td>NA</td>
  </tr>
  </tbody>
  </table>
  </div>
  <p>I can do this by concatenating the codes (via group_by and summarise) and then separating the codes into individual columns, but I imagine there's a more direct way to do this.</p>
  <p>Thanks for any suggestions!</p>