library(tidyverse)
## -- Attaching packages --------------------------------------- tidyverse 1.3.1 --
## v ggplot2 3.3.5     v purrr   0.3.4
## v tibble  3.1.6     v dplyr   1.0.7
## v tidyr   1.1.4     v stringr 1.4.0
## v readr   2.1.1     v forcats 0.5.1
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(USAboundaries)
## Warning: package 'USAboundaries' was built under R version 4.1.3
## The USAboundariesData package needs to be installed.
##  Please try installing the package using the following command: 
##      install.packages("USAboundariesData", repos = "https://ropensci.r-universe.dev", type = "source")
library(ggplot2)
library(sf)
## Warning: package 'sf' was built under R version 4.1.3
## Linking to GEOS 3.9.1, GDAL 3.2.1, PROJ 7.2.1; sf_use_s2() is TRUE
library(scales)
## Warning: package 'scales' was built under R version 4.1.3
## 
## Attaching package: 'scales'
## The following object is masked from 'package:purrr':
## 
##     discard
## The following object is masked from 'package:readr':
## 
##     col_factor
library(leaflet)
## Warning: package 'leaflet' was built under R version 4.1.3
library(maps)
## Warning: package 'maps' was built under R version 4.1.3
## 
## Attaching package: 'maps'
## The following object is masked from 'package:purrr':
## 
##     map
library(dplyr)
library(grid)
library(rgdal)
## Warning: package 'rgdal' was built under R version 4.1.3
## Loading required package: sp
## Please note that rgdal will be retired by the end of 2023,
## plan transition to sf/stars/terra functions using GDAL and PROJ
## at your earliest convenience.
## 
## rgdal: version: 1.5-28, (SVN revision 1158)
## 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/Asus/Documents/R/win-library/4.1/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/Asus/Documents/R/win-library/4.1/rgdal/proj
## PROJ CDN enabled: FALSE
## Linking to sp version:1.4-6
## To mute warnings of possible GDAL/OSR exportToProj4() degradation,
## use options("rgdal_show_exportToProj4_warnings"="none") before loading sp or rgdal.
## Overwritten PROJ_LIB was C:/Users/Asus/Documents/R/win-library/4.1/rgdal/proj
library(raster)
## Warning: package 'raster' was built under R version 4.1.3
## 
## Attaching package: 'raster'
## The following object is masked from 'package:dplyr':
## 
##     select

2. Load the data, and clean it up:

#dataset
newdata<- read.csv("1976-2020-president.csv", header = T)
head(newdata)
##   year   state state_po state_fips state_cen state_ic       office
## 1 1976 ALABAMA       AL          1        63       41 US PRESIDENT
## 2 1976 ALABAMA       AL          1        63       41 US PRESIDENT
## 3 1976 ALABAMA       AL          1        63       41 US PRESIDENT
## 4 1976 ALABAMA       AL          1        63       41 US PRESIDENT
## 5 1976 ALABAMA       AL          1        63       41 US PRESIDENT
## 6 1976 ALABAMA       AL          1        63       41 US PRESIDENT
##                 candidate             party_detailed writein candidatevotes
## 1           CARTER, JIMMY                   DEMOCRAT   FALSE         659170
## 2            FORD, GERALD                 REPUBLICAN   FALSE         504070
## 3          MADDOX, LESTER AMERICAN INDEPENDENT PARTY   FALSE           9198
## 4 BUBAR, BENJAMIN ""BEN""                PROHIBITION   FALSE           6669
## 5               HALL, GUS        COMMUNIST PARTY USE   FALSE           1954
## 6         MACBRIDE, ROGER                LIBERTARIAN   FALSE           1481
##   totalvotes  version notes party_simplified
## 1    1182850 20210113    NA         DEMOCRAT
## 2    1182850 20210113    NA       REPUBLICAN
## 3    1182850 20210113    NA            OTHER
## 4    1182850 20210113    NA            OTHER
## 5    1182850 20210113    NA            OTHER
## 6    1182850 20210113    NA      LIBERTARIAN
#State map of usa
map("state")

newdata$color <- ifelse(newdata$party_simplified =="DEMOCRAT","Blue", 
                        ifelse(newdata$party_simplified =="REPUBLICAN", "Red", "White"))

typeof(newdata$color)
## [1] "character"
##final
data_new2 <- newdata %>%                             
  group_by(state, year) %>%
  slice_max(candidatevotes)   # Top N highest values by group

final <- data_new2  %>% arrange(data_new2$year)

neededvar <- c("year", "state", "state_fips", "party_simplified", "candidate", "color")

myEdata <- final[neededvar]

head(myEdata)
## # A tibble: 6 x 6
## # Groups:   state, year [6]
##    year state      state_fips party_simplified candidate     color
##   <int> <chr>           <int> <chr>            <chr>         <chr>
## 1  1976 ALABAMA             1 DEMOCRAT         CARTER, JIMMY Blue 
## 2  1976 ALASKA              2 REPUBLICAN       FORD, GERALD  Red  
## 3  1976 ARIZONA             4 REPUBLICAN       FORD, GERALD  Red  
## 4  1976 ARKANSAS            5 DEMOCRAT         CARTER, JIMMY Blue 
## 5  1976 CALIFORNIA          6 REPUBLICAN       FORD, GERALD  Red  
## 6  1976 COLORADO            8 REPUBLICAN       FORD, GERALD  Red

Question 1 Part 1

temp <- filter(myEdata, year==2000)
temp <- temp[match(state.fips$fips, temp$state_fips), ]

map("state", col=temp$color, fill=TRUE)
legend("bottomright", bty="n", legend=c("Democrat", "Republican", "Others"), fill = c("blue", "red", "white"), cex=0.8, title = "Candidates")
title("Presidential Election Results by State in 2000", line=1)

Question 1 Part 2

Presidential lection results by year and state

years=seq(1976, 2020, by=4)
par(mfrow=c(3,4), mar=c(0,0,0,0))

for (i in years) {
        temp <- filter(myEdata, year==i)
        temp <- temp[match(state.fips$fips, temp$state_fips), ]
        map("state", col=temp$color, fill=T)
        mtext(i,side=3,line=1)
}

legend("bottomleft", inset = c(-0.15, -0.6), xpd=TRUE, legend = c("Democrat", "Republican", "Others"), fill=c("blue", "red", "white"), bty = "n", title = "Presidential election results by year and state",cex=0.6)

Part 2: Interactive Maps with Leaflet

1. Get familiar with the leaflet package

Open Street Map

myMap <- leaflet() %>%
  addProviderTiles(providers$OpenStreetMap)
myMap %>% setView(lat=33.947474, lng=-83.373671, zoom = 12) #for Athens area

Topographic map

TopoMap <- leaflet() %>%
  addProviderTiles(providers$OpenTopoMap)
TopoMap %>% setView(lat=33.947474, lng=-83.373671, zoom = 7) #for Athens area

Esri.NatGeoWorldMap

Esrimap <- leaflet() %>%
  addProviderTiles(providers$Esri.NatGeoWorldMap)
Esrimap %>% setView(lat=33.947474, lng=-83.373671, zoom = 12) #for Athens area

Add your own shapefiles

#loading the dataset 
zipF<- "C:\\Users\\Asus\\OneDrive - University of Georgia\\PhD\\Spring 2022\\AAEC 8610\\220130_rrc_outline_block_al2.zip"
outDir<- "C:\\Users\\Asus\\OneDrive - University of Georgia\\PhD\\Spring 2022\\AAEC 8610\\dataset"
unzip(zipF,exdir=outDir)
sp <- shapefile("C:/Users/Asus/OneDrive - University of Georgia/PhD/Spring 2022/AAEC 8610/T220130_RRC_Outline_Block_AL2.shp")

# Projection is necessary for R to place the coordinates correctly
campShapeFile <- spTransform(sp, CRS("+proj=longlat +datum=WGS84 +no_defs"))
head(campShapeFile)
##   OBJECTID_1 OBJECTID Block_Let Camp_SSID Block_Name   Block_SSID SMSD_Cname
## 0          1        1         I   CXB-232     C04X_I CXB-232_I163   Camp 04X
## 1          2        2         B   CXB-232     C04X_B CXB-232_B165   Camp 04X
## 2          3        3         F   CXB-232     C04X_F CXB-232_F161   Camp 04X
## 3          4        4         C   CXB-232     C04X_C CXB-232_C166   Camp 04X
## 4          5        5         E   CXB-232     C04X_E CXB-232_E160   Camp 04X
## 5          6        6         H   CXB-232     C04X_H CXB-232_H162   Camp 04X
##         Camp_Alias         NPM_Cname Area_Acres         CampName
## 0 Camp 4 Extension Camp 04 Extension  17.579304 Camp 4 Extension
## 1 Camp 4 Extension Camp 04 Extension  19.796469 Camp 4 Extension
## 2 Camp 4 Extension Camp 04 Extension   8.892700 Camp 4 Extension
## 3 Camp 4 Extension Camp 04 Extension  40.189147 Camp 4 Extension
## 4 Camp 4 Extension Camp 04 Extension  17.429451 Camp 4 Extension
## 5 Camp 4 Extension Camp 04 Extension   8.238809 Camp 4 Extension
##           Area_SqM  Shape_Leng  Shape_Le_1   Shape_Area
## 0 71140.9196299387 0.012361753 0.012361755 6.192077e-06
## 1 80113.4668634516 0.010098287 0.010098287 6.973411e-06
## 2 35987.4806593324 0.007094379 0.007094378 3.132450e-06
## 3 162639.706686226 0.023266098 0.023266094 1.415641e-05
## 4 70534.4857807752 0.013253804 0.013253802 6.139350e-06
## 5 33341.2781127569 0.006681391 0.006681390 2.901994e-06

• Zoom your map onto South-Eastern Bangladesh (setView(92.14871, 21.18780, zoom = 12)) • Add the shapefile to your map with:

Rohinga <- leaflet(campShapeFile) %>%
addPolygons(color = "#74C476", weight = 1, smoothFactor = 0.5,
              opacity = 1.0, fillOpacity = 0.7,
              label = campShapeFile$Block_No,
              highlightOptions = highlightOptions(color = "white", weight = 2,
                                                  bringToFront = TRUE))

Rohinga %>% setView(lat= 21.18780, lng=92.14871, zoom = 13)

3. Add tiles from the web

• Start a new leaflet map and zoom onto the USA. • See what happens when you add these tiles (with %>% of course):

leaflet() %>% 
  addProviderTiles(providers$OpenStreetMap) %>% 
  setView(lat=35.227085, lng=-80.843124, zoom = 7) %>%
addWMSTiles("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi",
  layers = "nexrad-n0r-900913",
  options = WMSTileOptions(format = "image/png", transparent = TRUE),
  attribution = "Weather data © 2012 IEM Nexrad")