<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/zero-counts-in-dplyr/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://kieranhealy.org/blog/archives/2018/11/19/zero-counts-in-dplyr/"> R on kieranhealy.org</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Here’s a feature of <code>dplyr</code> that occasionally bites me (most recently while making <a rel="nofollow" href="https://kieranhealy.org/blog/archives/2018/11/17/congress-over-time/" target="_blank">these graphs</a>). It’s about to change mostly for the better, but is also likely to bite me again in the future. If you want to follow along there’s a GitHub repo with the <a rel="nofollow" href="https://github.com/kjhealy/fc_sample" target="_blank">necessary code and data</a>.</p>
<p>Say we have a data frame or tibble and we want to get a frequency table or set of counts out of it. In this case, each row of our data is a person serving a congressional term for the very first time, for the years 2013 to 2019. We have information on the term year, the party of the representative, and whether they are a man or a woman.</p>
<div>
<pre><code data-lang="r">

<span>library</span><span>(</span>tidyverse<span>)</span>

<span>## Hex colors for sex</span>
sex_colors <span>&lt;-</span> <span>c</span><span>(</span><span>&quot;#E69F00&quot;</span><span>,</span> <span>&quot;#993300&quot;</span><span>)</span>

<span>## Hex color codes for Dem Blue and Rep Red</span>
party_colors <span>&lt;-</span> <span>c</span><span>(</span><span>&quot;#2E74C0&quot;</span><span>,</span> <span>&quot;#CB454A&quot;</span><span>)</span>

<span>## Group labels</span>
mf_labs <span>&lt;-</span> tibble<span>(</span>M <span>=</span> <span>&quot;Men&quot;</span><span>,</span> <span>F</span> <span>=</span> <span>&quot;Women&quot;</span><span>)</span>

theme_set<span>(</span>theme_minimal<span>())</span>

<span>## Character vectors only, by default</span>
df <span>&lt;-</span> read_csv<span>(</span><span>&quot;data/fc_sample.csv&quot;</span><span>)</span>

df

<span>#> > df</span>
<span>#> # A tibble: 280 x 4</span>
<span>#> pid start_year party sex</span>
<span>#> </span></code></pre></div>