title: Merge frequency table with existing data frame based on ID
body: <h3>What I have:</h3>
  
  <p>From my original observations …</p>
  
  <pre><code>video_id  user_id keyword
  1         1       foo
  2         1       bar
  3         1       baz
  4         1       yak
  1         2       foo
  2         2       bar
  3         2       blah
  4         2       yak
  1         3       foo
  2         3       bar
  3         3       blah
  4         3       yak
  </code></pre>
  
  <p>… I have a table with frequencies (called <code>tab</code>), and it is displayed in the exact format I want, e.g.</p>
  
  <pre><code>video_id  foo bar baz yak blah
  1         4   0   0   0   0
  2         0   4   0   0   0
  3         0   0   2   0   2
  4         0   0   0   4   0
  </code></pre>
  
  <p>I'd like to merge this table with an existing data frame (called <code>data</code>), based on the ID column. So, for example, it contains two other columns as well:</p>
  
  <pre><code>video_id  col1  col2
  1         123   412
  2         652   633
  3         749   144
  4         1738  1763
  </code></pre>
  
  <h3>What I need:</h3>
  
  <p>I need to merge the frequency table and the existing data frame based on the video ID. Note that it is not necessarily sorted, so I can't just <code>cbind</code> them. This is the result I need:</p>
  
  <pre><code>video_id  col1  col2  foo bar baz yak blah
  1         123   412   4   0   0   0   0
  2         652   633   0   4   0   0   0
  3         749   144   0   0   2   0   2
  4         1738  1763  0   0   0   4   0
  </code></pre>
  
  <p>Now, I know I can get a data frame matrix like this:</p>
  
  <pre><code>as.data.frame.matrix(table(…))
  </code></pre>
  
  <p>But this matrix is missing the <code>video_id</code> column, which is actually displayed when I just view the table. So, how do I go about getting a data frame that still includes the <code>video_id</code> column—or row names, that is?</p>
  
  <p>I need the <code>video_id</code> column to come first in the data frame, then the original columns, and <em>then</em> the tabular data appended, as seen in the example above.</p>
  
  <h3>What I've tried:</h3>
  
  <ul>
  <li><p>I know I can get the table's row names through <code>rownames(table(…))</code>, and I can get the result I want with</p>
  
  <pre><code>cbind(data.frame(video_id=rownames(tab)), as.data.frame.matrix(tab))
  </code></pre>
  
  <p>But this doesn't seem clean (enough) to me.</p></li>
  <li><p>Merging directly with</p>
  
  <pre><code>merge(data, as.data.frame.matrix(tab))
  </code></pre>
  
  <p>gives me all the results, but the <code>video_id</code> column is between the tabular data and the original data, so not in the correct order.</p></li>
  </ul>