title: How to calculate new column depending on aggregate function on group using dplyr (add summary statistics on the summary statistics)?
body: <p>Quite often I need to calculate a new column for an R dataframe (in long form), whose value should depend on an aggregate function (e.g. sum) of a group. For instance, I might want to know what fraction of sales a product accounts for on any given day:</p>
  
  <pre><code>daily fraction = revenue for product i on day d / sum or revenue for all products on day d
  </code></pre>
  
  <p>My current strategy is to summarise and join:</p>
  
  <pre><code>library(dplyr)
  
  join_summary &lt;- function(data, ...) left_join(data, summarise(data, ...))
  
  data = data.frame(
    day = c(1,1,2,2,3,3),
    product = rep(c("A", "B"), 3),
    revenue = c(2, 4, 8, 7, 9, 2)
  )
  
  data2 &lt;- data %&gt;%
    group_by(day) %&gt;%
    join_summary(daily_revenue = sum(revenue)) %&gt;%
    mutate(revenue_fraction = revenue / daily_revenue)
  </code></pre>
  
  <p>This works, but I am not sure if it is an anti-pattern. It seems a bit inefficient to repeat the same data (the daily revenue) on multiple rows, littering my data frame with aggregates. My questions are:</p>
  
  <ul>
  <li>Is my current way of doing it OK?</li>
  <li>Is there any better way of doing it, preferably using tools from <code>dplyr</code> or the wider Hadleyverse?</li>
  <li>Do I really need my custom function <code>join_summary</code>, or can it be done with the existing <code>dplyr</code> verbs? (I prefer to stay within the "pipe flow", though.)</li>
  </ul>