2016 U.S. Presidential Election Project Logan Rasmussen July 2021 This project is a general analysis of the 2016 U.S. presidential election. The document was made using R Markdown in RStudio. The goal of this project is to manipulate census and election data sets to pull basic information from the data, create election maps, and perform primary component analysis and decision tree pruning to gather insight about voting behavior. Background The 2016 U.S. presidential election between Hillary Clinton and Donald Trump did not have the outcome many people and pollster expected. Polls overestimated Clinton’s chance of winning, causing Trump’s eventual win to blindside the world. To better understand what happened, one must look at what happens before election day. Voting polls are conducted many months before election day to assess the voting behavior of the American population. Statistical models use the data gathered from the polls to predict what the outcome of election day voting could be, however these models, each with their own differences, were more wrong than right this election. Or, more accurate to say, had just enough error for something unexpected to happen. This error is small but important, and it is up to pollsters, politicians, and data scientists to learn more about the unknown factors that lead to this. Some statisticians such as Nate Silver were able to accurately predict the 2012 presidential election but faced the same problems others faced in 2016. The first step to predicting the outcome are the polls. Voting polls are conducted at a national and state level, thus making the process hierarchical in nature. Both levels must be taken into account, but national and state characteristics don’t reflect each other one-to-one. A similar relationship can be attributed to people before election day, and people on election day. The data sampled from polls more so explains how people think they will vote on election day than how people will vote on election day. There are factors within the pollsters and the samples themselves that also alter results. The house effect, or the natural bias of the pollsters, may skew results in favor of one candidate compared to others. There is also sampling variation, which is a expected and essential part of statistics. To examine voter bias, the estimates must be compared with the actual votes, however votes from the previous election can be used to conduct the examination as well, albeit not as accurate. A simple formula to calculate the actual votes can be considered the likelihood—actual percentage + house effect + sampling variation. For his model, Silver applied Bayes’ Theorem to his calculations to update predictions over time. No matter the model, the knowledge of what factors effect voting behavior must get more robust. The common trait many of the polls shared was that they overwhelmingly favored Clinton to Trump. The polling error was systematic; it is apparent that there was an inherent problem with how the polls were conducted and/or how the future predictions were calculated. 1 Data The project_data.RData binary file used in this project contains three datasets: tract-level 2010 census data, stored as census ; metadata census_meta with variable descriptions and types; and county-level vote tallies from the 2016 election, stored as election_raw # Load the data into R load( ' data/project_data.RData ' ) Election data Example rows of the election data are shown below: filter(election_raw, !is.na(county)) %>% head() %>% pander() county fips candidate state votes Los Angeles County 6037 Hillary Clinton CA 2464364 Los Angeles County 6037 Donald Trump CA 769743 Los Angeles County 6037 Gary Johnson CA 88968 Los Angeles County 6037 Jill Stein CA 76465 Los Angeles County 6037 Gloria La Riva CA 21993 Cook County 17031 Hillary Clinton IL 1611946 The fips column in election_raw is an acronym short for “Federal Information Processing Standard.” In this dataset, fips values denote the area (nationwide, statewide, or countywide) that the rows of the data represent. Federal-level summary rows have a fips value of US and state-level summary rows have the state name as the fips value. Rows with fips=2000 are filtered out due to having NA values under the county column. Rows with numbered fips values should have a corresponding county name. Federal-level and state-level rows do not have a number value under fips , thus it is ok for these rows to have NA values under the county column. election_raw %>% filter(!(fips == 2000)) ## # A tibble: 18,345 x 5 ## county fips candidate state votes ## <chr> <chr> <chr> <chr> <dbl> ## 1 <NA> US "Donald Trump" US 62984825 ## 2 <NA> US "Hillary Clinton" US 65853516 ## 3 <NA> US "Gary Johnson" US 4489221 ## 4 <NA> US "Jill Stein" US 1429596 ## 5 <NA> US "Evan McMullin" US 510002 ## 6 <NA> US "Darrell Castle" US 186545 ## 7 <NA> US "Gloria La Riva" US 74117 ## 8 <NA> US "Rocky De La Fuente" US 33010 ## 9 <NA> US " None of these candidates" US 28863 ## 10 <NA> US "Richard Duncan" US 24235 ## # ... with 18,335 more rows The new dataset has 18,345 rows and 5 columns. 2 Census data The first few rows and columns of the census data are shown below. census %>% select(1:6) %>% head() %>% pander(digits = 15) CensusTract State County TotalPop Men Women 1001020100 Alabama Autauga 1948 940 1008 1001020200 Alabama Autauga 2156 1059 1097 1001020300 Alabama Autauga 2968 1364 1604 1001020400 Alabama Autauga 4423 2172 2251 1001020500 Alabama Autauga 10763 4922 5841 1001020600 Alabama Autauga 3851 1787 2064 Variable descriptions are given in the metadata file. The variables shown above are: census_meta %>% head() %>% pander() variable description type CensusTract Census tract ID numeric State State, DC, or Puerto Rico string County County or county equivalent string TotalPop Total population numeric Men Number of men numeric Women Number of women numeric 3 Data Preprocessing The rows of election_raw are separated into federal-, state-, and county-level data frames: * Federal-level tallies as ` election_federal ` * State-level tallies as ` election_state ` * County-level tallies as ` election ` . The ` fips ` variable is coerced to numeric. # Federal-level tallies election_federal <- election_raw %>% filter(fips == "US") # State-level tallies election_state <- election_raw %>% filter(fips %in% c("AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY")) # County-level tallies (includes "US") election <- election_raw %>% filter(!(fips %in% c("AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH","OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY", "US"))) election$fips <- as.numeric(election$fips) # Coercing ` fips ` variable to numeric 4 There were 32 named presidential candidates in the 2016 election. A bar graph of all votes received by each candidate in decreasing order visualizes the rank of presidential candidates in terms of their votes. The vote axis was log-transformed to create a smaller gap visually between the lower and higher ranked presidential candidates. # Summing candidate votes candi_order <- as.data.frame(aggregate(election_raw$votes, by = list(candidate = election_raw$candidate) # Correct ordering of the candidates ordering <- candi_order[order(-candi_order$x), ] # Creating the bar graph + log-transform vote_count_bg <- ggplot(ordering, aes(x = fct_reorder(candidate, log(x), max), y = log(x))) + geom_bar(stat = "identity", fill = "steelblue") + coord_flip() + theme_minimal() + labs(x = "Candidates", y = "Number of Votes") vote_count_bg Frank Atwood Jerry White Bradford Lyttle Princess Jacob Ryan Scott Rod Silva Michael Maturen Joseph Maldonado Kyle Kopitke Laurence Kotlikoff Tom Hoefling Scott Copeland Emidio Soltysik Rocky Giordani Peter Skewes Monica Moorehead Jim Hedges Lynn Kahn Chris Keniston Mike Smith Alyson Kennedy Dan Vacek Richard Duncan None of these candidates Rocky De La Fuente Gloria La Riva Darrell Castle Evan McMullin Jill Stein Gary Johnson Donald Trump Hillary Clinton 0 5 10 15 20 Number of Votes Candidates The bar graph appears to show a tight race between the candidates, but in reality Clinton and Trump shared the majority of the votes. Clinton won the popular vote, just skimming above Trump. In an election these few million votes that make the difference are capable of being the deciding factor. If Clinton had even just a few more million votes, possibly even less, it could mean her winning the states that Trump won, and thus the election. 5 The data sets county_winner and state_winner are created by taking the candidate with the highest proportion of votes. The rows pair the winning candidates with the county and/or state in which they won. county_winner <- election %>% select(fips, candidate, votes, state, county) %>% group_by(fips) %>% # Group by county mutate(total_county = sum(votes)) %>% # Calculate total votes mutate(pct_county = votes/total_county) %>% # Calculate percentage of votes slice_max(pct_county) # Candidate with highest percentage of votes in group county_winner ## # A tibble: 3,113 x 7 ## # Groups: fips [3,113] ## fips candidate votes state county total_county pct_county ## <dbl> <chr> <dbl> <chr> <chr> <dbl> <dbl> ## 1 1001 Donald Trump 18172 AL Autauga County 24759 0.734 ## 2 1003 Donald Trump 72883 AL Baldwin County 94261 0.773 ## 3 1005 Donald Trump 5454 AL Barbour County 10436 0.523 ## 4 1007 Donald Trump 6738 AL Bibb County 8753 0.770 ## 5 1009 Donald Trump 22859 AL Blount County 25442 0.898 ## 6 1011 Hillary Clinton 3530 AL Bullock County 4702 0.751 ## 7 1013 Donald Trump 4901 AL Butler County 8705 0.563 ## 8 1015 Donald Trump 32865 AL Calhoun County 47485 0.692 ## 9 1017 Donald Trump 7843 AL Chambers County 13839 0.567 ## 10 1019 Donald Trump 8953 AL Cherokee County 10673 0.839 ## # ... with 3,103 more rows state_winner <- election_state %>% select(state, candidate, votes, fips) %>% group_by(state) %>% # Group by state mutate(total_state = sum(votes)) %>% # Calculate total votes mutate(pct_state = votes/total_state) %>% # Calculate percentage of votes slice_max(pct_state) # Candidate with highest proportion of votes in group state_winner ## # A tibble: 51 x 6 ## # Groups: state [51] ## state candidate votes fips total_state pct_state ## <chr> <chr> <dbl> <chr> <dbl> <dbl> ## 1 AK Donald Trump 163387 AK 309407 0.528 ## 2 AL Donald Trump 1318255 AL 2101660 0.627 ## 3 AR Donald Trump 684872 AR 1130635 0.606 ## 4 AZ Donald Trump 1252401 AZ 2554240 0.490 ## 5 CA Hillary Clinton 8753788 CA 14060856 0.623 ## 6 CO Hillary Clinton 1338870 CO 2780220 0.482 ## 7 CT Hillary Clinton 897572 CT 1642304 0.547 ## 8 DC Hillary Clinton 282830 DC 304717 0.928 ## 9 DE Hillary Clinton 235603 DE 441590 0.534 ## 10 FL Donald Trump 4617886 FL 9419886 0.490 ## # ... with 41 more rows 6 Visualization Maps of the election data are generated using ggmap State Map states <- map_data("state") ggplot(states) + geom_polygon(aes(x = long, y = lat, fill = region, group = group), color = "white") + coord_fixed(1.3) + # Avoid stretching guides(fill = FALSE) + # No fill legend theme_nothing() # No axes County Map counties <- map_data("county") ggplot(counties) + geom_polygon(aes(x = long, y = lat, fill = region, group = group), color = "white", size = 0.1) + coord_fixed(1.3) + # Avoid stretching guides(fill = FALSE) + # No fill legend theme_nothing() # No axes 7 To map the winning candidate for each state, the map data ( states ) must be merged with with the election data ( state_winner ). The function left_join() combines the data frames, but the states data frame uses full state names while election_state uses state abbreviations. A fips variable needs to be created in the states data frame to match the fips variable in election_state # Change full state name to abbreviation name2abb <- function (statename){ ix <- match(statename, tolower(state.name)) out <- state.abb[ix] return(out) } # Apply change to data frame states <- states %>% mutate(fips = name2abb(states$region)) head(states) ## long lat group order region subregion fips ## 1 -87.46201 30.38968 1 1 alabama <NA> AL ## 2 -87.48493 30.37249 1 2 alabama <NA> AL ## 3 -87.52503 30.37249 1 3 alabama <NA> AL ## 4 -87.53076 30.33239 1 4 alabama <NA> AL ## 5 -87.57087 30.32665 1 5 alabama <NA> AL ## 6 -87.58806 30.32665 1 6 alabama <NA> AL left_join(df1, df2) takes the rows from df1 and matches with the rows of df2 . If no matching value is found, it adds missing values. # ` Left_join ` to merge the tables states_statesWinner <- states %>% left_join(state_winner) ## Joining, by = "fips" 8 Election Results State Map ggplot(states_statesWinner) + geom_polygon(aes(x = long, y = lat, fill = candidate, group = group), color = "white", size = 0.1) + coord_fixed(1.3) + # Avoid stretching guides(colour = "colorbar") + # No fill legend theme(panel.border = element_blank(), panel.background = element_rect(fill = "white"), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.ticks.x = element_blank(), axis.ticks.y = element_blank(), axis.title.x = element_blank(), axis.title.y = element_blank(), axis.text.x = element_blank(), axis.text.y = element_blank()) candidate Donald Trump Hillary Clinton NA Looking at the map, Clinton won the coastal states (except in the south) as well as Colorado, New Mexico, Minnesota, and Illinois. The coastal states are known “blue” states, largely in part due to influential coastal cities and an overall denser and more diverse population, so it is no surprise Clinton won there. The few non-coastal states she did win may have been won due certain state-wide demographic and/or lifestyle changes. To see why Trump won the rest of the states, a county election map should be created. 9 To create a county-level map, information from maps::county.fips is used to give the county-level map data a fips value. The polyname column is separated to region and subregion using tidyr::separate , and left_join() is used to combine county.fips with the county-level map data. # Change to abbreviations counties <- counties %>% mutate(region = name2abb(counties$region)) # Information from ` maps::county.fips ` state_fips <- maps::county.fips # Separate ` polyname ` column state_fips <- state_fips %>% separate("polyname", c("region", "subregion"), "([\\,])") # Adding ` state_fips ` to ` county_winner ` data frame map_region <- county_winner %>% left_join(state_fips) ## Joining, by = "fips" # Change to abbreviations map_data <- map_region %>% mutate(region = name2abb(region)) # Combining county data with map data counties_countyWinner <- counties %>% left_join(map_data) ## Joining, by = c("region", "subregion") 10 Election Results County Map ggplot(counties_countyWinner) + geom_polygon(aes(x = long, y = lat, fill = candidate, group = group), color = "white", size = 0.1) + coord_fixed(1.3) + # Avoid stretching guides(colour = "colorbar") + # No fill legend theme(panel.border = element_blank(), panel.background = element_rect(fill = "white"), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.ticks.x = element_blank(), axis.ticks.y = element_blank(), axis.title.x = element_blank(), axis.title.y = element_blank(), axis.text.x = element_blank(), axis.text.y = element_blank()) candidate Donald Trump Hillary Clinton NA Looking at the map, Trump won a large majority of the counties. Although a majority of the U.S. population lives in a minority of the counties, Trump won too many counties for Clinton have the edge. Many of the counties in red are rural, many of them inland and not locations of large, important American cities. Demographic trends associated with the county election map will be explored further in. The demographic characteristics between Clinton voters and Trump voters can be compared by making density graphs. The purpose of the visualizations are to what type of demographics are more likely to vote for either Clinton or Trump. The x-axis is measured by increasing value of the variable, while the y-axis is the proportion of the demographic that Clinton and Trump have. 11 hist_data <- map_region %>% left_join(census) get_legend<- function (myggplot){ tmp <- ggplot_gtable(ggplot_build(myggplot)) leg <- which(sapply(tmp$grobs, function (x) x$name) == "guide-box") legend <- tmp$grobs[[leg]] return(legend) } # Create visualizations p1 <- ggplot(data = hist_data, aes(x = Income, group = candidate, fill = candidate)) + geom_density(adjust = 1.5, alpha = .4, position = "fill") + labs(title = "County Voting by Income") + theme_bw() p2 <- ggplot(data = hist_data, aes(x = (Unemployment), group = candidate, fill = candidate)) + geom_density(adjust = 1.5, alpha = .4, position = "fill") + labs(title = "County Voting by Unemployment") + theme_bw() p3 <- ggplot(data = hist_data, aes(x = (Professional), group = candidate, fill = candidate)) + geom_density(adjust = 1.5, alpha = .4, position = "fill") + labs(title = "Voting by Professional") + theme_bw() p4 <- ggplot(data = hist_data, aes(x = (Service), group = candidate, fill = candidate)) + geom_density(adjust = 1.5, alpha = .4, position = "fill") + labs(title = "Voting by Service") + theme_bw() p5 <- ggplot(data = hist_data, aes(x = (Office), group = candidate, fill = candidate)) + geom_density(adjust = 1.5, alpha = .4, position = "fill") + labs(title = "Voting by Office") + theme_bw() p6 <- ggplot(data = hist_data, aes(x = (Construction), group = candidate, fill = candidate)) + geom_density(adjust = 1.5, alpha = .4, position = "fill") + labs(title = "Voting by Construction") + theme_bw() p7 <- ggplot(data = hist_data, aes(x = (Production), group = candidate, fill = candidate)) + geom_density(adjust = 1.5, alpha = .4, position = "fill") + labs(title = "Voting by Production") + theme_bw() legend <- get_legend(p1) 12 # Visualization organizing grid.arrange(p1 + theme(legend.position = "none"), p2 + theme(legend.position = "none"), p3 + theme(legend.position = "none"), p4 + theme(legend.position = "none"), p5 + theme(legend.position = "none"), p6 + theme(legend.position = "none"), p7 + theme(legend.position = "none"), legend, ncol=4, nrow =3) 13 The census data is aggregated into county-level data by computing population-weighted averages of each attribute for each county and carrying out the following steps: • Clean census data, saving the result as census_del : – filter out any rows of census with missing values; – convert Men , Employed , and Citizen to percentages; – compute a Minority variable by combining Hispanic , Black , Native , Asian , Pacific , and remove these variables after creating Minority ; and – remove Walk , PublicWork , and Construction # Remove NA values, create pct for Men, Employed, and Citizen census_cleaning <- na.omit(census) %>% mutate(Men_pct = Men/TotalPop, Employed_pct = Employed/TotalPop, Citizen_pct = Citizen/TotalPop, Minority = Hispanic + Black + Native + Asian + Pacific) # Remove Walk, PublicWork, Construction columns census_del <- subset(census_cleaning, select = -c(Men, Employed, Citizen, Hispanic, Black, Native, Asian, Pacific, Walk, PublicWork, Construction # Rename and finalize census_del census_del <- census_del %>% dplyr::rename(Men = Men_pct, Employed = Employed_pct, Citizen = Citizen_pct) head(census_del) ## # A tibble: 6 x 30 ## CensusTract State County TotalPop Women White Income IncomeErr IncomePerCap ## <dbl> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> ## 1 1001020100 Alab~ Autau~ 1948 1008 87.4 61838 11900 25713 ## 2 1001020200 Alab~ Autau~ 2156 1097 40.4 32303 13538 18021 ## 3 1001020300 Alab~ Autau~ 2968 1604 74.5 44922 5629 20689 ## 4 1001020400 Alab~ Autau~ 4423 2251 82.8 54329 7003 24125 ## 5 1001020500 Alab~ Autau~ 10763 5841 68.5 51965 6935 27526 ## 6 1001020600 Alab~ Autau~ 3851 2064 72.9 63092 9585 30480 ## # ... with 21 more variables: IncomePerCapErr <dbl>, Poverty <dbl>, ## # ChildPoverty <dbl>, Professional <dbl>, Service <dbl>, Office <dbl>, ## # Production <dbl>, Drive <dbl>, Carpool <dbl>, Transit <dbl>, ## # OtherTransp <dbl>, WorkAtHome <dbl>, MeanCommute <dbl>, PrivateWork <dbl>, ## # SelfEmployed <dbl>, FamilyWork <dbl>, Unemployment <dbl>, Men <dbl>, ## # Employed <dbl>, Citizen <dbl>, Minority <dbl> 14 • Create population weights for sub-county census data, save the result as census_subct : – group census_del by State and County ; – use add_tally() to compute CountyPop ; – compute the population weight as TotalPop/CountyTotal ; – adjust all quantitative variables by multiplying by the population weights. # Draft of census_subct census_draft <- census_del %>% group_by(State, County) %>% add_tally(TotalPop) # Total population of county census_draft <- census_draft %>% dplyr::rename(CountyTotal = n) %>% mutate(PopWeight = TotalPop/CountyTotal) # Finalize census_subct census_subct <- census_draft[4:32]*census_draft$PopWeight census_subct$State <- census_draft$State census_subct$County <- census_draft$County head(census_subct) ## TotalPop Women White Income IncomeErr IncomePerCap ## 1 68.71849 35.55865 3.083160 2181.424 419.7896 907.063 ## 2 84.17696 42.83030 1.577342 1261.210 528.5657 703.596 ## 3 159.52308 86.21126 4.004201 2414.453 302.5456 1111.986 ## 4 354.26611 180.29686 6.631977 4351.554 560.9147 1932.324 ## 5 2097.79195 1138.45608 13.351180 10128.380 1351.6851 5365.030 ## 6 268.56089 143.93915 5.083897 4399.907 668.4384 2125.613 ## IncomePerCapErr Poverty ChildPoverty Professional Service Office ## 1 160.43722 0.2857391 0.2963221 1.2240923 0.5996994 0.7513881 ## 2 96.59267 0.9955995 1.5734376 0.8706615 0.9643650 0.8394270 ## 3 151.40718 0.6825954 1.0588291 1.6876768 1.3383169 1.1878235 ## 4 229.87650 0.1682023 0.1281541 2.1626012 1.6660039 2.1626012 ## 5 548.27546 2.2219482 3.4108854 9.6674236 2.7676898 3.5473208 ## 6 526.52161 1.0042267 1.5272614 1.6876587 1.2204143 2.4687239 ## Production Drive Carpool Transit OtherTransp WorkAtHome MeanCommute ## 1 0.5362018 3.181934 0.1693269 0 0.08113580 0.07408051 0.8819109 ## 2 0.8589486 3.369421 0.5114648 0 0.02733018 0.00000000 0.9136090 ## 3 0.6664711 5.095279 0.1504935 0 0.00000000 0.13436917 1.0534543 ## 4 1.3135800 6.936343 0.7288767 0 0.20825048 0.12815414 2.0264374 ## 5 3.0795422 17.151881 2.0465312 0 0.11694464 0.17541696 4.8337118 ## 6 1.0390956 5.767329 0.4811919 0 0.41842777 0.31382083 1.3808116 ## PrivateWork SelfEmployed FamilyWork Unemployment Men Employed ## 1 2.719813 0.1622716 0 0.1904927 0.01702251 0.01707684 ## 2 3.006320 0.2381630 0 0.5192735 0.01917749 0.01363612 ## 3 3.445226 0.6610963 0 0.3332355 0.02470075 0.02486373 ## 4 6.063293 0.2482987 0 0.8650405 0.03933286 0.03227033 ## 5 13.078309 1.0330110 0 0.8186125 0.08913276 0.09121530 ## 6 5.537194 0.4044802 0 0.7601438 0.03236088 0.02825012 ## Citizen Minority CountyTotal PopWeight State County ## 1 0.02721791 0.3351261 1948 0.001244427 Alabama Autauga ## 2 0.03009725 2.2020318 2156 0.001524365 Alabama Autauga ## 3 0.04228464 1.1179515 2968 0.002888812 Alabama Autauga 15 ## 4 0.05986853 1.2655222 4423 0.006415424 Alabama Autauga ## 5 0.13882400 5.7107966 10763 0.037989025 Alabama Autauga ## 6 0.04784412 1.7434491 3851 0.004863383 Alabama Autauga 16 • Aggregate census data to county level, census_ct : group the sub-county data census_subct by state and county and compute popluation-weighted averages of each variable by taking the sum. census_ct <- census_subct %>% group_by(State, County) %>% dplyr::summarise(across(TotalPop:CountyTotal, sum)) ## ` summarise() ` regrouping output by ' State ' (override with ` .groups ` argument) census_ct ## # A tibble: 3,218 x 30 ## # Groups: State [52] ## State County TotalPop Women White Income IncomeErr IncomePerCap ## <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> ## 1 Alab~ Autau~ 6486. 3349. 75.8 51696. 7771. 24974. ## 2 Alab~ Baldw~ 7699. 3934. 83.1 51074. 8745. 27317. ## 3 Alab~ Barbo~ 3325. 1492. 46.2 32959. 6031. 16824. ## 4 Alab~ Bibb 6381. 2930. 74.5 38887. 5662. 18431. ## 5 Alab~ Blount 7019. 3562. 87.9 46238. 8696. 20532. ## 6 Alab~ Bullo~ 4263. 1968. 22.2 33293. 9000. 17580. ## 7 Alab~ Butler 2531. 1354. 53.3 32517. 6585. 18390. ## 8 Alab~ Calho~ 4925. 2544. 73.0 42424. 6895. 21373. ## 9 Alab~ Chamb~ 4327. 2270. 57.3 34217. 7550. 21071. ## 10 Alab~ Chero~ 4387. 2196. 91.7 37183. 4653. 21811. ## # ... with 3,208 more rows, and 22 more variables: IncomePerCapErr <dbl>, ## # Poverty <dbl>, ChildPoverty <dbl>, Professional <dbl>, Service <dbl>, ## # Office <dbl>, Production <dbl>, Drive <dbl>, Carpool <dbl>, Transit <dbl>, ## # OtherTransp <dbl>, WorkAtHome <dbl>, MeanCommute <dbl>, PrivateWork <dbl>, ## # SelfEmployed <dbl>, FamilyWork <dbl>, Unemployment <dbl>, Men <dbl>, ## # Employed <dbl>, Citizen <dbl>, Minority <dbl>, CountyTotal <dbl> 17 Now that the census data is aggregated into county-level data, demographic information can be looked up for individual counties. For example, the demographics and voting counts for Sacramento County, CA, is shown below. # Information for Sacramento, CA # Demographic Info census_ct %>% filter(County == "Sacramento") %>% pander() Table 4: Table continues below State County TotalPop Women White Income IncomeErr California Sacramento 5360 2750 46.95 60478 9087 Table 5: Table continues below IncomePerCap IncomePerCapErr Poverty ChildPoverty Professional 27461 3752 18.17 23.77 36.22 Table 6: Table continues below Service Office Production Drive Carpool Transit OtherTransp 20 26.04 9.478 75.98 11.71 2.91 2.297 Table 7: Table continues below WorkAtHome MeanCommute PrivateWork SelfEmployed FamilyWork 5.037 26.39 71.17 7.263 0.1939 Unemployment Men Employed Citizen Minority CountyTotal 12.07 0.4865 0.435 0.671 47.95 1457103 # County Results election %>% filter(fips == unique(election$fips[which((election$state == "CA") & election$county == "Sacramento County")])) %>% pander() county fips candidate state votes Sacramento County 6067 Hillary Clinton CA 326023 Sacramento County 6067 Donald Trump CA 189789 Sacramento County 6067 Gary Johnson CA 24412 Sacramento County 6067 Jill Stein CA 9846 Sacramento County 6067 Gloria La Riva CA 2556 18 # State Results state_winner %>% filter(fips == "CA") %>% select(state, candidate, votes) %>% pander() state candidate votes CA Hillary Clinton 8753788 In California, Clinton had 8,753,788 votes, accounting for 61.73% of the total votes in California. Trump had 4,483,810 votes in California, accounting for 31.62% of the total votes in California. In Sacramento County, Clinton had 59% of the votes while Trump had 34.34% of the votes. Overall, Sacramento County is a couple percentage points more red than California in general, but not by much. Sacramento County is a diverse and bustling region, but compared to the counties with larger population densities in coastal California regions, may have a smaller population of woman and minorities and more rural land that may explain these percentage differences. 19 Exploratory analysis Primary Component Analysis is a dimension-reducing process to find the components which affect variance the most. Components that affect variance the most, in other words, have the most influence. In this case, Primary Component Analysis is used to see which factors influence voting behavior the most. The first two principal components PC1 and PC2 for both county and sub-county respectively. County # Remove "State" and "Country" columns census_ct_numeric <- census_ct[, -c(1, 2, 3)] # Centering and scaling of data census_ct_mx <- census_ct_numeric %>% scale(center = T, scale = T) # Compute SVD census_ct_svd <- svd(census_ct_mx) # Get loadings cc_v_svd <- census_ct_svd$v # Compute PCs census_ct_pc <- census_ct_mx %*% cc_v_svd census_ct_pc_plot <- census_ct_pc[, 1:2] %>% as.data.frame() %>% dplyr::rename(PC1 = V1, PC2 = V2) %>% bind_cols(select(census_ct)) %>% ggplot(aes(x = PC1, y = PC2)) + geom_point(aes(alpha = 0.5)) + theme_bw() ## Adding missing grouping variables: ` State ` census_ct_pc_plot 20