title: Aggregating data with ggplot
body: <p>Let's use the <code>mpg</code> dataset as an example, specifically the <code>class</code> and <code>cyl</code> columns. I can see how many entries are there, per single <code>class</code>, and differentiate the fill color based on the cyl value:</p>
  
  <pre><code>library(ggplot2)
  p &lt;- ggplot(mpg)
  p &lt;- p + geom_bar(mapping=aes(x=class, fill=factor(cyl)), position=position_dodge())
  print(p)
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/CnYHw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/CnYHw.png" alt="enter image description here"></a></p>
  
  <p>What I'd like to see, though, is the <strong>average</strong> count of entries (per <code>class</code>), per different values of <code>cyl</code>. Basically, if you look at the plot above, I want a single bar per class, whose height should be the average height of the colored bars for that class.</p>
  
  <p>I am able to get this result by preprocessing the data frame, e.g.:</p>
  
  <pre><code>df &lt;- aggregate(formula=cyl~class, data=mpg, FUN=function(x) { length(x) / length(unique(x)) })
  p &lt;- ggplot(df)
  p &lt;- p + geom_bar(mapping=aes(x=class, y=cyl), stat='identity')
  p &lt;- p + ylab('average count')
  </code></pre>
  
  <p>That gives my <strong>desired output</strong>:</p>
  
  <p><a href="https://i.stack.imgur.com/BqGVS.png" rel="noreferrer"><img src="https://i.stack.imgur.com/BqGVS.png" alt="enter image description here"></a></p>
  
  <p>However, given how powerful ggplot2 is, I am wondering if this is possible through ggplot functions. I guess this involves using a specific <code>stat</code> (maybe with <code>group=cyl</code>?), but I am not able to.</p>