Please document your answers to all homework questions using R Markdown, submitting your compiled output as a zipped .html folder (this is necessary when using plotly and leaflet).
\(~\)
A precinct is the smallest geographic unit for which aggregated voting data is publicly available. For this question, you will work with precinct-level election data for the state of Iowa from the 2020 US presidential election. These data were acquired through Harvard’s Dataverse, and were published by the Voting and Election Science Team in 2020 (https://doi.org/10.7910/DVN/K7760H).
To begin, you should download this zipped folder and extract it to an accessible location on your PC. The code below reads these data on my PC (note that I have the iowa_precincts folder in my downloads).
library(leaflet)
library(maptools)
iowa <- readShapeSpatial("C:/Users/millerry/Downloads/iowa_precincts/ia_2020") ## You will need to change this file path
In Part A your goal is to create a ggplot
map where each
precinct is colored according the margin by which it favored Donald
Trump (votes recorded in “G20PRERTRU”) or Joe Biden (votes recorded in
“G20PREDBID”). The code below creates a new variable, “MARGIN”, that you
can use for this purpose.
## Relative difference in Trump vs. Biden votes
iowa@data$MARGIN = (iowa@data$G20PRERTRU - iowa@data$G20PREDBID)/(
iowa@data$G20PRERTRU + iowa@data$G20PREDBID +
iowa@data$G20PRELJOR + iowa@data$G20PREGHAW)
Your final result should look something like the map below (it does not need to resemble it exactly, but it should be similar):
\(~\)
In Part B your goal is to make an interactive leaflet map of Poweshiek County (home to Grinnell), Jasper County (just west of Grinnell), and Polk County (home to Des Moines) showing each precinct’s name and vote totals for Donald Trump and Joe Biden when you hover over it. The map should also include a highlight that clearly displays which precinct the user is hovering over.
You may use the following code to subset the spatial polygons file to include only Poweshiek County.
## Create subset (note that pow_co is a spatial polygons file, just like "iowa")
pow_co <- iowa[iowa$COUNTY %in% c("Poweshiek", "Jasper", "Polk"), ]
Your final result should look something like the map below (it doesn’t need to be exactly identical):