1.2 Election data download and preparation
Now we’re going to download 2020 county-level election results from a GitHub repo. You can read more about the data in the repo.
## 2020 Election data
<- read_csv("https://raw.githubusercontent.com/tonmcg/US_County_Level_Election_Results_08-20/master/2020_US_County_Level_Presidential_Results.csv")
dta2020
## Calculate percentages based on total votes for Trump and Biden (GOP and Dem) only
## In some years there have been ties, so we're allowing for that
## stdVotes and stdVotesLog will be used to scale color opacitiy from 0 to 1 based on total votes
<- dta2020 %>%
dta2020 mutate(pctGOP = votes_gop/(votes_gop + votes_dem),
totalVotes = votes_gop + votes_dem,
winner = ifelse(dta2020$votes_gop > dta2020$votes_dem,"Trump",
ifelse(dta2020$votes_gop < dta2020$votes_dem,"Biden",
"Tie")),
pctWinner = ifelse(dta2020$votes_gop > dta2020$votes_dem,pctGOP,1-pctGOP),
FontColorWinner = ifelse(dta2020$votes_gop > dta2020$votes_dem,"red",
ifelse(dta2020$votes_gop < dta2020$votes_dem,"blue",
"purple")),
pctGOPcategories = ifelse(pctGOP<0.48,"0-48%",
ifelse(pctGOP<0.5,"48-50%",
ifelse(pctGOP<0.52, "50-52%",
"52-100%"))),
stdVotes = (totalVotes-min(totalVotes))/(max(totalVotes)-min(totalVotes)),
stdVotesLog = (log(totalVotes)-min(log(totalVotes)))/(max(log(totalVotes))-min(log(totalVotes)))
)
<- dta2020 %>%
dta2020 select(FIPS = county_fips, pctGOP, totalVotes, winner, pctWinner, pctGOPcategories, FontColorWinner, stdVotes, stdVotesLog)
## merge GIS data with voting data
<- left_join(countyGIS,dta2020,by="FIPS")
countyGIS
## For maps, drop the following:
## Hawaii (ST FIPS 15) (so our map can zoom in on continental 48 states)
<- countyGIS %>% filter(stFIPS != "15") countyGIS_map