<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/better-grouped-summaries-in-dplyr/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.win-vector.com/blog/2017/07/better-grouped-summaries-in-dplyr/"> R – Win-Vector Blog</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>For <a rel="nofollow" href="https://cran.r-project.org/" target="_blank"><code>R</code></a> <a rel="nofollow" href="https://cran.r-project.org/package=dplyr" target="_blank"><code>dplyr</code></a> users one of the promises of the new <a rel="nofollow" href="https://cran.r-project.org/package=rlang" target="_blank"><code>rlang</code>/<code>tidyeval</code></a> system is an improved ability to <a rel="nofollow" href="http://dplyr.tidyverse.org/articles/programming.html" target="_blank">program over <code>dplyr</code></a> itself. In particular to add new verbs that encapsulate previously compound steps into better self-documenting atomic steps.</p>
<p>Let’s take a look at this capability.</p>
<p><span></span></p>
<p>First let’s start <code>dplyr</code>.</p>
<div>
<pre><code><span>suppressPackageStartupMessages</span>(<span>library</span>(<span>&quot;dplyr&quot;</span>))
<span>packageVersion</span>(<span>&quot;dplyr&quot;</span>)</code></pre>
</div>
<pre><code>## [1] '0.7.1.9000'</code></pre>
<p>A <code>dplyr</code> pattern that I have seen used often is the &quot;<code>group_by() %>% mutate()</code>&quot; pattern. This historically has been shorthand for a &quot;<code>group_by() %>% summarize()</code>&quot; followed by a <code>join()</code>. It is easiest to show by example.</p>
<p>The following code:</p>
<div>
<pre><code>mtcars %>%<span> </span>
<span> </span><span>group_by</span>(cyl, gear) %>%
<span> </span><span>mutate</span>(<span>group_mean_mpg =</span> <span>mean</span>(mpg), 
            <span>group_mean_disp =</span> <span>mean</span>(disp)) %>%<span> </span>
<span> </span><span>select</span>(cyl, gear, mpg, disp, group_mean_mpg, group_mean_disp) %>%
<span> </span><span>head</span>()</code></pre>
</div>
<pre><code>## # A tibble: 6 x 6
## # Groups:   cyl, gear [4]
##     cyl  gear   mpg  disp group_mean_mpg group_mean_disp
##   </code></pre>