Richard Sprague

My personal website

Aggregating local election results in R

Richard Sprague / 2016-12-11

National and local news outlets report the results of the Presidential election at the state and county level, but that doesn’t tell me how my neighborhood voted. For that I’ll need the precinct-by-precinct results, which in my area is not reported. Can I calculate it myself? In R the answer is of course a big YES. Here’s how I did it.

First load the following R packages:


Next obtain the full King County election results as a precinct-by-precint CSV file.

Filter the results to look for just the Mercer Island precincts, and further narrow down to just the US Presidential results.

mercerIsland2016<- filter(election2016,startsWith(as.character(Precinct),"M-I"))
mi.president.all<-filter(mercerIsland2016,Race=="US President & Vice President")   %>% 

#mi.president.all %>% group_by(candidate) %>% summarize(sum=sum(sum)) %>% arrange(desc(sum))

mi.president.all %>% filter(candidate!="Times Counted" &
                              candidate!="Registered Voters") %>%
  group_by(candidate) %>% 
  summarize(sum=sum(sum)) %>%
  arrange(desc(sum)) %>%
  mutate(pct=sum/sum(sum)*100) %>%
candidate sum pct
Hillary Clinton & Tim Kaine 10721 69.244
Donald J. Trump & Michael R. Pence 3272 21.133
Gary Johnson & Bill Weld 578 3.733
Write-In 438 2.829
Times Blank Voted 290 1.873
Jill Stein & Ajamu Baraka 139 0.898
Darrell L. Castle & Scott N. Bradley 31 0.200
Gloria Estela La Riva & Eugene Puryear 7 0.045
Times Over Voted 4 0.026
Alyson Kennedy & Osborne Hart 3 0.019

Top Candidates

Sometimes it’s nice to compare just among votes case for the “top candidates”, like this:

topCandidates<-c("Donald J. Trump & Michael R. Pence",
                 "Gary Johnson & Bill Weld",
                 "Jill Stein & Ajamu Baraka",
                 "Hillary Clinton & Tim Kaine")

mi.president<-mi.president.all %>% filter(candidate %in% topCandidates)
mi.president.all$candidate<-factor(mi.president$candidate)<-mi.president %>% group_by(candidate) %>%
  summarize(sum=sum(sum)) %>%
  arrange(desc(sum)) %>%

candidate sum pct
Hillary Clinton & Tim Kaine 10721 72.882
Donald J. Trump & Michael R. Pence 3272 22.243
Gary Johnson & Bill Weld 578 3.929
Jill Stein & Ajamu Baraka 139 0.945

and that’s it!