## How big was the 2016 partisan swing in Mahoning County ## relative to the rest of the US? ## ## Christopher Adolph faculty.washington.edu/cadolph ## 14 May 2017 ## Load data from my website; originally from downloaded 14 May 2017 from ## https://github.com/tonmcg/County_Level_Election_Results_12-16 folder <- "http://faculty.washington.edu/cadolph/409/" data2012 <- read.csv(paste0(folder, "US_County_Level_Presidential_Results_08-16.csv")) data2016 <- read.csv(paste0(folder, "2016_US_County_Level_Presidential_Results.csv")) ## Rename FIPS variable for easy merging data2016$fips_code <- data2016$combined_fips ## Merge dataframes (common column is county FIPS code) dataAll <- merge(data2012, data2016) ## Compute %Democratic - %Republican vote for president partisanship2012 <- with(dataAll, (dem_2012 - gop_2012)/total_2012) partisanship2016 <- with(dataAll, (per_dem - per_gop)) ## Compute swing from 2012 to 2016 partySwing <- partisanship2016 - partisanship2012 # Clean up data types (preserve character data) dataAll$county <- as.character(dataAll$county) dataAll$state_abbr <- as.character(dataAll$state_abbr) ## Save relevant columns to new dataframe res <- with(dataAll, as.data.frame( cbind(county, state_abbr, total_votes, per_dem, per_gop, partySwing))) ## Clean up data types (avoid conversion to factors) res$partySwing <- as.numeric(as.character(res$partySwing)) res$per_dem <- as.numeric(as.character(res$per_dem)) res$per_gop <- as.numeric(as.character(res$per_gop)) ## Sort by partisan swing res <- res[order(res$partySwing),] ## Subset to include only counties with 100k or more total votes res2 <- res[as.numeric(as.character(res$total_votes))>=100000,] res2$rank <- 1:nrow(res2) ## Save result to csv file write.csv(res2, "swing.csv") ## Print the first few rows: Mahoning was number 1! print(head(res2))