<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/the-zero-bug/"></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/02/the-zero-bug/"> R – Win-Vector Blog</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>I am going to write about an insidious statistical, data analysis, and presentation fallacy I call “the zero bug” and the habits you need to cultivate to avoid it.</p>
<p><center><br>
<img title="The zero bug" alt="The zero bug" src="https://i2.wp.com/www.win-vector.com/blog/wp-content/uploads/2017/02/pic45.png?resize=600%2C480" border="0" data-recalc-dims="1">
<p>The zero bug<br>
</center></p>
<p>Here is the zero bug in a nutshell: common data aggregation tools often can not “count to zero” from examples, and this causes problems. Please read on for what this means, the consequences, and how to avoid the problem.<span></span></p>
<p>
<h2>Our Example</h2>
<p>For our example problem please consider aggregating significant earthquake events in the United States of America. </p>
<p>To do this we will start with data from: </p>
<blockquote><p><a target="_blank" rel="nofollow" href="https://www.ngdc.noaa.gov/nndc/struts/form?t=101650&s=1&%23038;d=1">The National Geophysical Data Center / World Data Service (NGDC/WDS): Significant Earthquake Database</a>, National Geophysical Data Center, NOAA, <a target="_blank" rel="nofollow" href="http://dx.doi.org/10.7289/V5TD9V7K">doi:10.7289/V5TD9V7K</a>.
</p>
</blockquote>
<p>They database is described thusly:</p>
<blockquote><p>The Significant Earthquake Database contains information on destructive earthquakes from 2150 B.C. to the present that meet at least one of the following criteria: Moderate damage (approximately $1 million or more), 10 or more deaths, Magnitude 7.5 or greater, Modified Mercalli Intensity X or greater, or the earthquake generated a tsunami.</p>
</blockquote>
<p>I queried the form for “North America and Hawaii”:”USA” in tab delimited form. For simplicity and reproducibility I saved a the result in the url given in the <a target="_blank" rel="nofollow" href="https://cran.r-project.org/"><code>R</code></a> example below. Starting our example we can use <code>R</code> to load the data from the url and start our project.</p>
<pre>
url &lt;- 'http://www.win-vector.com/dfiles/earthquakes.tsv'
d &lt;- read.table(url, 
                header=TRUE, 
                stringsAsFactors = FALSE,
                sep='\t')
View(d)
head(d[,c('I_D','YEAR','INTENSITY','STATE')])
#    I_D YEAR INTENSITY STATE
# 1 6697 1500        NA    HI
# 2 6013 1668         4    MA
# 3 9954 1700        NA    OR
# 4 5828 1755         8    MA
# 5 5926 1788         7    AK
# 6 5927 1788        NA    AK
</pre>
<p>We see the data is organizes such that each row is an event (with <code>I_D</code>), and contains many informational columns including “YEAR” (the year the event happened) and “STATE” (the state abbreviation where the event happened). Using <code>R</code> tools and packages we can immediately start to summarize and visualize the data.</p>
<p>For example: we can count modern (say 1950 and later) US earthquakes by year.</p>
<pre>
library(&quot;ggplot2&quot;)
library(&quot;dplyr&quot;)

dModern &lt;- d[d$YEAR>=1950, , drop=FALSE]

# histogram
ggplot(data=dModern, mapping=aes(x=YEAR)) +
  geom_histogram(binwidth=1) +
  ggtitle('number of modern USA earthquakes by year')
</pre>
<p><img title="NewImage.png" alt="NewImage" src="https://i2.wp.com/www.win-vector.com/blog/wp-content/uploads/2017/02/NewImage-1.png?w=660" border="0" data-recalc-dims="1"></p>
<p>Or we can get use <code>dplyr</code> to build the count summaries by hand and present the summary in a stem-plot instead of the histogram.</p>
<pre>
# aggregate the data
byYear &lt;- dModern %>% 
  group_by(YEAR) %>%
  summarize(count = n()) %>%
  arrange(YEAR)

# produce a stem-style plot
ggplot(data=byYear, mapping=aes(x=YEAR, y=count)) +
  geom_point(color='darkgreen') +
  geom_segment(mapping=aes(xend=YEAR, yend=0),
               color='darkgreen') +
  scale_y_continuous(limits=c(0, max(byYear$count))) +
  ggtitle('number of modern USA earthquakes by year')
</pre>
<p><img title="NewImage.png" alt="NewImage" src="https://i0.wp.com/www.win-vector.com/blog/wp-content/uploads/2017/02/NewImage-2.png?w=660" border="0" data-recalc-dims="1"></p>
<h2>The problem</h2>
<p>We have already snuck in the mistake. The by-hand aggregation “<code>byYear</code>” is subtly wrong. The histogram is almost correct (given its graphical convention of showing counts as height), but the stem plot is revealing problems.</p>
<p>Here is the problem:</p>
<pre>
summary(byYear$count)

#    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
#    1.00    1.00    2.00    2.50    3.75    7.00 
</pre>
<p>Notice the above summary implies the minimum number of significant earthquakes seen in the United States in a modern year is <code>1</code>. Looking at our graphs we can see it should in fact be <code>0</code>. This wasn’t so bad for graphing, but can be disastrous in calculation or in directing action.</p>
<h2>The fix</h2>
<p>This is the kind of situation that <code>anti_join</code> is designed to fix (and is how <code><a target="_blank" rel="nofollow" href="https://cran.r-project.org/package=replyr">replyr</a>::replyr_coalesce</code> deals with the problem).</p>
<p>A simple ad-hoc fix I recommend is to build a second synthetic summary frame that carries explicit zero counts. We then add these counts into our aggregation and get correct summaries.</p>
<p>For example the following code:</p>
<pre>
# add in zero summaries
zeroObs &lt;- data.frame(YEAR=1950:2016, count=0)
byYear &lt;- rbind(byYear, zeroObs) %>%
  group_by(YEAR) %>%
  summarize(count = sum(count)) %>%
  arrange(YEAR)

# re-plot
ggplot(data=byYear, mapping=aes(x=YEAR, y=count)) +
  geom_point(color='darkgreen') +
  geom_segment(mapping=aes(xend=YEAR, yend=0),
               color='darkgreen') +
  scale_y_continuous(limits=c(0, max(byYear$count))) +
  ggtitle('number of modern USA earthquakes by year')
</pre>
<p>gives us the corrected stem plot:</p>
<p><img title="NewImage.png" alt="NewImage" src="https://i0.wp.com/www.win-vector.com/blog/wp-content/uploads/2017/02/NewImage-3.png?w=660" border="0" data-recalc-dims="1"></p>
<p>The figure above is the correct stem-plot. Remember: while a histogram denotes counts by filled-heights of bars, a stem-plot denotes counts by positions of visible points. The point being: in a proper stem-plot zero counts are not invisible (and are in fact distinguishable from missing summaries).</p>
<h2>A harder example</h2>
<p>This issue may seem trivial but that is partly because I deliberately picked a simple example where it is obvious there is missing data. This is not always the case. Remember: hidden errors can be worse than visible errors. In fact even in the original histogram it was not obvious what to think about the missing years 1950 (which apparently had no significant US earthquakes) and 2017 (which is an incomplete year). We really have to explicitly specify the complete universe (also called range or support set) of keys (as in <code>YEAR=1950:2016</code>, and not use a convenience such as <code>YEAR=min(dModern$YEAR):max(dModern$YEAR)</code>).</p>
<p>This is much more obvious if we summarize by state instead of year.</p>
<pre>
byState &lt;- dModern %>% 
  group_by(STATE) %>%
  summarize(count = n()) %>%
  arrange(STATE)

ggplot(data=byState, mapping=aes(x=STATE, y=count)) +
  geom_point(color='darkgreen') +
  geom_segment(mapping=aes(xend=STATE, yend=0),
               color='darkgreen') +
  scale_y_continuous(limits=c(0, max(byState$count))) +
  ggtitle('number of modern USA earthquakes by state')
</pre>
<p><img title="NewImage.png" alt="NewImage" src="https://i2.wp.com/www.win-vector.com/blog/wp-content/uploads/2017/02/NewImage-4.png?w=660" border="0" data-recalc-dims="1"></p>
<p>We do not have a proper aggregation where each state count is represented with an explicit zero, and not by implicit missingness (which can’t differentiate states with zero-counts from non-states or misspellings). To produce the proper summary we need a <a target="_blank" rel="nofollow" href="https://en.wikipedia.org/wiki/List_of_U.S._state_abbreviations">list of US state abbreviations</a> to merge in.</p>
<p>A user of the above graph isn’t likely to be too confused. Such a person likely knows there are 50 states and will presume the missing states have zero counts. However downstream software (which can be punishingly literal) won’t inject such domain knowledge and will work on the assumption that there are 17 states and all states have had significant earthquakes in modern times. Or suppose we are aggregating number treatments given to a set of patients; in this case the unacceptable confusion of not-present and zero-counts can really hide huge, problems: such as not noticing some patients never received treatment.</p>
<p><code>R</code> actually has list of state abbreviations (in “<code>datasets::state.abb</code>“) and we can use <code>replyr::replyr_coalesce</code> to quickly fix our issue:</p>
<pre>
library('replyr')

support &lt;- data.frame(STATE= c('', datasets::state.abb),
                      stringsAsFactors = FALSE)

byState &lt;- byState %>%
  replyr_coalesce(support,
                  fills= list(count= 0)) %>%
  arrange(STATE)
</pre>
<p>An important feature of <code>replyr_coalesce</code> is: it checks that the count-carrying rows (the data) are contained in the support rows (the range definition). It would (intentionally) throw an error if we tried to use just <code>datasets::state.abb</code> as the support (or range) definition as this signals the analyst didn’t expect the blank state in the data set.</p>
<h2>“The Dog that Didn’t Bark”</h2>
<p>An additional illustrative example is from Sir Arthur Conan Doyle’s story “The Adventure of Silver Blaze”. </p>
<p><img title="NewImage.png" alt="NewImage" src="https://i0.wp.com/www.win-vector.com/blog/wp-content/uploads/2017/02/NewImage-5.png?w=660" border="0" data-recalc-dims="1"></p>
<p>In this story Sherlock Holmes deduces that a horse had been absconded not by a stranger, but by somebody well known at its stable. Holmes explains the key clue here:</p>
<pre>
   Gregory (Scotland Yard): &quot;Is there any other point to which you 
                             would wish to draw my attention?&quot;
   Holmes: &quot;To the curious incident of the dog in the night-time.&quot;
   Gregory: &quot;The dog did nothing in the night-time.&quot;
   Holmes: &quot;That was the curious incident.&quot;
</pre>
<p>For this type of reasoning to work: Holmes has to know that there was a dog present, the dog would have barked if a stranger approached the stables, and none of his witnesses reported hearing the dog. Holmes needs an affirmative record that no barks were heard: a zero written in a row, not a lack of rows.</p>
<h2>Conclusion</h2>
<p>When describing “common pitfalls” the reaction is often: “That isn’t really interesting, as <em>I</em> would never make such an error.” I believe “the zero bug” is in fact common and not noticed as it tends to hide. The bug is often there and invisible, but can produce invalid results.</p>
<p>Any summary that is produced by counting un-weighted rows can never explicitly produce a value of zero (it can only hint at such through missingness). <code>n()</code> can never form zero, so if zero is important it <em>must</em> be explicitly joined in after counting. In a sense organizing rows for counting with <code>n()</code> censors out zeros.</p>
<p>I can’t emphasize enough how important it is to only work with explicit representations (records indicating counts, even if they are zero), and not implicit representations (assuming non-matched keys indicate zero-counts). The advantages of explicit representations are one of the reasons <code>R</code> has a notation for missing values (“<code>NA</code>“) in the first place.</p>
<p>This is, of course, not a problem due to use of <code>dplyr</code>. This is a common problem in designing <code>SQL</code> database queries where you can think of it as “inner-join collapse” (failing to notice rows that disappear due to join conditions).</p>
<p>My advice: you should be suspicious of any use of <code>summarize(VALUE=n())</code> until you find the matching zero correction (<code>replyr_coalesce</code>, or a comment documenting why no such correction is needed). This looking from <code>n()</code> to a matching range-control should be become as habitual as looking from an opening parenthesis to its matching closing parenthesis. Even in data science, you really have to know you have all the little things right before you rely on the large things.</p>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://www.win-vector.com/blog/2017/02/the-zero-bug/"> R – Win-Vector Blog</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/MF3F_sHPqwg"></a></div>