library(tidyverse)
## -- Attaching packages --------------------------------------- tidyverse 1.3.0 --
## v ggplot2 3.3.3     v purrr   0.3.4
## v tibble  3.0.6     v dplyr   1.0.3
## v tidyr   1.1.2     v stringr 1.4.0
## v readr   1.4.0     v forcats 0.5.1
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(tmap)
## Warning: package 'tmap' was built under R version 4.0.5
library(tmaptools)
## Warning: package 'tmaptools' was built under R version 4.0.5
library(leaflet)
## Warning: package 'leaflet' was built under R version 4.0.5
library(sf)
## Warning: package 'sf' was built under R version 4.0.5
## Linking to GEOS 3.9.0, GDAL 3.2.1, PROJ 7.2.1
library(leaflet.extras)
## Warning: package 'leaflet.extras' was built under R version 4.0.5
library(dplyr)
library(rio)
## Warning: package 'rio' was built under R version 4.0.5
library(sp)
## Warning: package 'sp' was built under R version 4.0.5
library(scales)
## 
## Attaching package: 'scales'
## The following object is masked from 'package:purrr':
## 
##     discard
## The following object is masked from 'package:readr':
## 
##     col_factor
setwd("C:/Users/noahz/Desktop/Data 110 R/Datasets/Hate crime data sets/GIS")
nhdata <- read_csv("NHD2016.csv")
## 
## -- Column specification --------------------------------------------------------
## cols(
##   .default = col_double(),
##   County = col_character()
## )
## i Use `spec()` for the full column specifications.
#View(nhdata)
nhdata <- nhdata[,c("County", "Clinton", "Sanders")]
nhdata$SandersMarginVotes <- nhdata$Sanders - nhdata$Clinton
nhdata$SandersPct <- (nhdata$Sanders - nhdata$Clinton) / (nhdata$Sanders + nhdata$Clinton)

nhdata$ClintonPct <- (nhdata$Clinton - nhdata$Sanders) / (nhdata$Sanders + nhdata$Clinton)
nhdata$SandersMarginPctgPoints <- nhdata$SandersPct - nhdata$ClintonPct
setwd("C:/Users/noahz/Desktop/Data 110 R/Datasets/Hate crime data sets/GIS/cb_2014_us_county_5m")
library(raster)
## Warning: package 'raster' was built under R version 4.0.5
## 
## Attaching package: 'raster'
## The following object is masked from 'package:dplyr':
## 
##     select
## The following object is masked from 'package:tidyr':
## 
##     extract
library(rgdal)
## Warning: package 'rgdal' was built under R version 4.0.5
## rgdal: version: 1.5-23, (SVN revision 1121)
## Geospatial Data Abstraction Library extensions to R successfully loaded
## Loaded GDAL runtime: GDAL 3.2.1, released 2020/12/29
## Path to GDAL shared files: C:/Users/noahz/Documents/R/win-library/4.0/rgdal/gdal
## GDAL binary built with GEOS: TRUE 
## Loaded PROJ runtime: Rel. 7.2.1, January 1st, 2021, [PJ_VERSION: 721]
## Path to PROJ shared files: C:/Users/noahz/Documents/R/win-library/4.0/rgdal/proj
## PROJ CDN enabled: FALSE
## Linking to sp version:1.4-5
## To mute warnings of possible GDAL/OSR exportToProj4() degradation,
## use options("rgdal_show_exportToProj4_warnings"="none") before loading rgdal.
## Overwritten PROJ_LIB was C:/Users/noahz/Documents/R/win-library/4.0/rgdal/proj
usgeo <- shapefile("cb_2014_us_county_5m.shp")
## Warning in rgdal::readOGR(dirname(x), fn, stringsAsFactors = stringsAsFactors, :
## Z-dimension discarded
qtm(usgeo)

nhgeo <- usgeo[usgeo@data$STATEFP == "33",]
#qtm(nhgeo)
str(nhgeo$NAME)
##  chr [1:10] "Grafton" "Hillsborough" "Coos" "Belknap" "Rockingham" ...
str(nhdata$County)
##  chr [1:10] "Belknap" "Carroll" "Cheshire" "Coos" "Grafton" "Hillsborough" ...
nhgeo <- nhgeo[order(nhgeo$NAME),]
nhdata <- nhdata[order(nhdata$County),]
identical(nhgeo$NAME,nhdata$County )
## [1] TRUE
nhmap <- merge(nhgeo, nhdata, by.x = "NAME", by.y = "County")
#str(nhmap)
qtm(nhmap, "SandersMarginVotes")
## Some legend labels were too wide. These labels have been resized to 0.62, 0.62, 0.62, 0.57, 0.53. Increase legend.width (argument of tm_layout) to make the legend wider and therefore the labels larger.

qtm(nhmap, "SandersMarginPctgPoints")

tm_shape(nhmap) +
  tm_fill("SandersMarginVotes", title="Sanders Margin, Total Votes", palette = "PRGn") +
  tm_borders(alpha = .5) +
  tm_text("NAME", size = 0.8)
## Warning in sp::proj4string(obj): CRS object has comment, which is lost in output
## Some legend labels were too wide. These labels have been resized to 0.62, 0.62, 0.62, 0.57, 0.53. Increase legend.width (argument of tm_layout) to make the legend wider and therefore the labels larger.

tm_shape(nhmap) +
  tm_fill("SandersMarginVotes", title = "Sanders Margin, Total Votes", palette = "PRGn") +
  tm_borders(alpha = .5) +
  tm_text("NAME", size = 0.8) + 
  tm_style("classic")
## Warning in sp::proj4string(obj): CRS object has comment, which is lost in output
## Some legend labels were too wide. These labels have been resized to 0.62, 0.62, 0.62, 0.57, 0.53. Increase legend.width (argument of tm_layout) to make the legend wider and therefore the labels larger.

nhstaticmap <- tm_shape(nhmap) +
  tm_fill("SandersMarginVotes", title="Sanders Margin, Total Votes", palette = "PRGn") +
  tm_borders(alpha = .5) +
  tm_text("NAME", size = 0.8)

tmap_save(nhstaticmap, filename = "nhdemprimary.jpg")
## Warning in sp::proj4string(obj): CRS object has comment, which is lost in output

## Warning in sp::proj4string(obj): CRS object has comment, which is lost in output
## Map saved to C:\Users\noahz\Desktop\Data 110 R\nhdemprimary.jpg
## Resolution: 1501.336 by 2937.385 pixels
## Size: 5.004452 by 9.791282 inches (300 dpi)
clintonPalette <- colorNumeric(palette = "Blues", domain = nhmap$ClintonPct)
nhpopup <- paste0("County: ", nhmap$County,
"Sanders ", percent(nhmap$SandersPct), " - Clinton ", percent(nhmap$ClintonPct))
leaflet(nhmap) %>%
  addProviderTiles("CartoDB.Positron") %>%
  addPolygons(
    stroke = FALSE, 
    smoothFactor = 0.2,
    fillOpacity = .8, 
    popup = nhpopup,
    color = ~clintonPalette(nhmap$ClintonPct)
    )
setwd("C:/Users/noahz/Desktop/Data 110 R/Datasets/Hate crime data sets/GIS")
scdata <- read_csv("SCGOP2016.csv")
## 
## -- Column specification --------------------------------------------------------
## cols(
##   County = col_character(),
##   `Jeb Bush` = col_double(),
##   `Ben Carson` = col_double(),
##   `Ted Cruz` = col_double(),
##   `John R Kasich` = col_double(),
##   `Marco Rubio` = col_double(),
##   `Donald J Trump` = col_double(),
##   Total = col_double()
## )
#view(scdata)
scgeo <- usgeo[usgeo@data$STATEFP == "45",]
qtm(scgeo)

candidates <- colnames(scdata[2:7])
for(i in 2:7){
  j = i + 7
  temp <- scdata[[i]] / scdata$Total
  scdata[[j]] <- temp
  colnames(scdata)[j] <- paste0(colnames(scdata)[i], "Pct")
}  
winner <- colnames(scdata[2:7])
for(i in 1:nrow(scdata)){
  scdata$winner[i] <- names(which.max(scdata[i,2:7]))
}
## Warning: Unknown or uninitialised column: `winner`.
setwd("C:/Users/noahz/Desktop/Data 110 R/Datasets/Hate crime data sets/GIS")
scdegree <- rio::import("SCdegree.xlsx")
str(scgeo$NAME)
##  chr [1:46] "Edgefield" "Lee" "Horry" "Allendale" "Marion" "Dorchester" ...
str(scdata$County)
##  chr [1:46] "Abbeville" "Aiken" "Allendale" "Anderson" "Bamberg" "Barnwell" ...
scgeo$NAME <- as.character(scgeo$NAME)

scgeo <- scgeo[order(scgeo$NAME),]
scdata <- scdata[order(scdata$County),]

identical(scgeo$NAME,scdata$County )
## [1] TRUE
scmap <- merge(scgeo, scdata, by.x = "NAME", by.y = "County") 
minpct <- min(c(scdata$`Donald J TrumpPct`, scdata$`Marco RubioPct`, scdata$`Ted CruzPct`))

maxpct <- max(c(scdata$`Donald J TrumpPct`, scdata$`Marco RubioPct`, scdata$`Ted CruzPct`))
trumpPalette <- colorNumeric(palette = "Purples", domain=c(minpct, maxpct))

rubioPalette <- colorNumeric(palette = "Reds", domain = c(minpct, maxpct))

cruzPalette <- colorNumeric(palette = "Oranges", domain = c(minpct, maxpct))
winnerPalette <- colorFactor(palette=c("#984ea3", "#e41a1c"), domain = scmap$winner)

edPalette <- colorNumeric(palette = "Blues", domain = scmap$PctCollegeDegree)
scpopup <- paste0("County: ", scmap@data$County,
"Winner: ", scmap@data$winner,
"Trump: ", percent(scmap$Donald.J.TrumpPct),
"Rubio: ", percent(scmap$Marco.RubioPct),
"Cruz: ", percent(scmap$Ted.CruzPct),
"Pct w college ed: ", scmap$PctCollegeDegree, "% vs state-wide avg of 25%")
scmap <- sp::spTransform(scmap, "+proj=longlat +datum=WGS84")
leaflet(scmap) %>%
  addProviderTiles("CartoDB.Positron") %>%
  addPolygons(stroke = TRUE,
    weight = 1,
    smoothFactor = 0.2,
    fillOpacity = .75,
    popup = scpopup, 
    color = ~winnerPalette(scmap$winner),
    group = "Winners"
 ) %>%
    addLegend(position="bottomleft", colors = c("#984ea3", "#e41a1c"), labels = c("Trump", "Rubio"))
scGOPmap <- leaflet(scmap) %>%
  addProviderTiles("CartoDB.Positron") %>%
  addPolygons(stroke = TRUE,
              weight = 1,
              smoothFactor = 0.2,
              fillOpacity = .75,
              popup=scpopup, 
              color= ~winnerPalette(scmap$winner),
              group="Winners"
  ) %>% 
    addLegend(position="bottomleft", colors=c("#984ea3", "#e41a1c"), labels=c("Trump", "Rubio"))  %>%

  addPolygons(stroke=TRUE,
     weight=1,
     smoothFactor = 0.2, 
     fillOpacity = .75, 
     popup=scpopup, 
     color= ~trumpPalette(scmap$`Donald J TrumpPct`),
     group="Trump") %>%

  addPolygons(stroke=TRUE,
              weight=1,
              smoothFactor = 0.2, 
              fillOpacity = .75, 
              popup=scpopup, 
              color= ~rubioPalette(scmap$`Marco RubioPct`),
              group="Rubio") %>%

  addPolygons(stroke=TRUE,
              weight=1,
              smoothFactor = 0.2, 
              fillOpacity = .75, 
              popup=scpopup, 
              color= ~cruzPalette(scmap$`Ted CruzPct`),
              group="Cruz") %>%

  addPolygons(stroke=TRUE,
              weight=1,
              smoothFactor = 0.2, 
              fillOpacity = .75, 
              popup=scpopup, 
              color= ~edPalette(scdegree$PctCollegeDegree),
              group="College degs") %>%

  addLayersControl(
      baseGroups = c("Winners", "Trump", "Rubio", "Cruz", "College degs"),
      position = "bottomleft",
      options = layersControlOptions(collapsed = FALSE))

scGOPmap
# for saving as HTML
#saveWidget(widget=scGOPmap, file="scGOPprimary.html")
#library(htmlwidgets)