Here’s how I fixed a problem in R where charts showing counts over time didn’t look right because R wasn’t taking zeroes into account.
This is related to Kieran Healy’s Zero Counts in dplyr but I got the real fix from Kan Nishida’s Populating Missing Dates with Complete and Fill Functions in R and Exploratory, and I’m documenting it here for my own sake and to show it in pure R because I don’t use Exploratory.
Let’s say I have a data set that shows counts of something or other—let’s say sales of fountain pens—on various days through the year. The thing is, people don’t buy fountain pens every day, and we only know about days when they do sell them, so when we make a data frame, it only has some of the days in the year.
Fake it this way:
(As with all code I write, I assume there’s a better way to do it, but what I have works, so it’s good enough for now.)
d has our data and we want to chart it.
That’s not right. It’s joining up all the points, but what about all the days when 0 fountain pens were sold? They don’t show at all. The line never goes to 0. This is no good. Does
No. It’s carrying the y value (
count) along until there’s a new one to show, then it goes up or down. That’s no good because it never hits 0 either.
Now, in real life I’m making these numbers using
count, and according to the documentation it looks like setting .
drop = FALSE should fill in the zero values for the dates, but it didn’t, either because the data was set up the wrong way or I was doing it wrong. In any case, here’s how I got it to work. I complete all the dates and then convert all the NAs (which are used to fill up
count) with 0s.
And now it works and the line hits 0 on the days when no fountain pens were sold.