title: Calculate subtotals with dplyr and tidyr
body: <pre><code>expand.grid(country = c('Sweden','Norway', 'Denmark','Finland'),
              sport = c('curling','crosscountry','downhill')) %&gt;% 
      mutate(medals = sample(0:3, 12, TRUE)) -&gt; 
   data
  </code></pre>
  
  <p>Using reshape2's dcast achieves this in one line. Using custom names for the margins require extra steps.</p>
  
  <pre><code>library(reshape2)
  
  data %&gt;% 
    dcast(country ~  sport, margins = TRUE, sum) %&gt;% 
  
   # optional renaming of the margins `(all)`
    rename(Total = `(all)`) %&gt;% 
    mutate(country = ifelse(country == "(all)", "Total", country))
  </code></pre>
  
  <p>My dplyr + tidyr approach is verbose. What is the best (compact and readable) way of writing this using tidyr and dplyr. </p>
  
  <pre><code>library(dplyr)
  library(tidyr)
  
  data %&gt;% 
    group_by(sport) %&gt;% 
    summarise(medals = sum(medals)) %&gt;% 
    mutate(country = 'Total') -&gt;
    sport_totals
  
  data %&gt;% 
    group_by(country) %&gt;% 
    summarise(medals = sum(medals)) %&gt;% 
    mutate(sport = 'Total') -&gt;
    country_totals
  
  data %&gt;% 
    summarise(medals = sum(medals)) %&gt;% 
    mutate(sport = 'Total',
           country = 'Total') -&gt;
    totals
  
  data %&gt;% 
    bind_rows(country_totals, sport_totals, totals) %&gt;% 
    spread(sport, medals)
  </code></pre>