title: Add count of unique / distinct values by group to the original data
body: <p>I wish to count the number of unique values by grouping of a second variable, and then add the count to the existing data.frame as a new column. For example, if the existing data frame looks like this:</p>
  
  <pre><code>  color  type
  1 black chair
  2 black chair
  3 black  sofa
  4 green  sofa
  5 green  sofa
  6   red  sofa
  7   red plate
  8  blue  sofa
  9  blue plate
  10 blue chair
  </code></pre>
  
  <p>I want to add for each <code>color</code>, the count of unique <code>types</code> that are present in the data:</p>
  
  <pre><code>  color  type unique_types
  1 black chair            2
  2 black chair            2
  3 black  sofa            2
  4 green  sofa            1
  5 green  sofa            1
  6   red  sofa            2
  7   red plate            2
  8  blue  sofa            3
  9  blue plate            3
  10 blue chair            3
  </code></pre>
  
  <p>I was hoping to use <code>ave</code>, but can't seem to find a straightforward method that doesn't require many lines. I have >100,000 rows, so am also not sure how important efficiency is.</p>
  
  <p>It's somewhat similar to this issue: <a href="https://stackoverflow.com/questions/7450600/how-do-i-count-aggregate-values-from-a-data-frame-and-reincorporate-them-into-th">Count number of observations/rows per group and add result to data frame</a></p>