AAEC8610 HW5 Option 1
(Submitted to Dr. Filipski)1
Exploring Spatial Analysis and Mapping in R
This is the 5th Homework for the Ph.D. course AAEC8610 (Advanced Econometrics) with Dr. Mateusz Filipski. Here we are Mapping the US Presidential Elections from 1976 to 2016 . The goal of this task is to learn how spatial analysis is conducted in R and how beautiful and magical it is. Here, I have used the basic package library(maps).2
Optional task 1: Map presidential elections results with the maps package
1. Download the elections file from harvard database:
https://dataverse.harvard.edu/dataset.xhtml?persistentId=doi:10.7910/DVN/42MVDX
(you can download directly into R, but that’s for another day. For now do it by hand and save the file on your disk)
2. Load the data, and clean it up:
You should aim to make a dataset at the state*year level, with infomation on the party who won in that state and that year. Something like this:
3. Try to make a map just for one year:
If your data is in the right format, this takes very very command: - one command to subset data for just one a year - one command to select the observsations that match ‘state.fips$fips’ - one command to map
R code: Loading and Cleaning
library(maps) # Draw geographical maps.
library(mapdata) # Map databases.
library(Hmisc) # Miscellaneous useful functions.
## Load Your Data . I chose to download directly from the Website
url <- "https://dataverse.harvard.edu/api/access/datafile/:persistentId?persistentId=doi:10.7910/DVN/42MVDX/MFU99O"
mydat <- read.table(url, fill = TRUE, header = T, sep = "\t") ##,
head(mydat)
## Data Creation : [collapsing the data to state-year level]
group <- as.data.frame(mydat)
group$newparty <- ""
group$newparty[group$party == "republican"] <- "republican"
group$newparty[group$party == "democrat"] <- "democrat"
group$newparty[group$newparty == ""] <- "others"
group$newparty <- as.factor(group$newparty)
head(group)
library(dplyr)
group <- group %>% mutate(stateyr = paste(state, year)) %>% group_by(stateyr) %>%
top_n(1, candidatevotes) %>% select(year, state, state_fips, newparty, candidate)
summary(group)
group$color <- ""
group <- group %>% mutate(color = case_when(newparty == "republican" ~ "red", newparty ==
"democrat" ~ "blue", newparty == "others" ~ "white"))
summary(group)
head(group)R Code: Creating US Map For Presidential Elections
# This snippet of code is just removing files from my directory to replace with new stuff
#Check its existence
if (file.exists("maps.pdf"))
#Delete file if it exists
file.remove("maps.pdf")
#Check its existence
if (file.exists("maps.png"))
#Delete file if it exists
file.remove("maps.png")
#Check its existence
if (file.exists("maps.jpg"))
#Delete file if it exists
file.remove("maps.jpg")
## LET's Program Our MAPPING CODE:
while (!is.null(dev.list())) dev.off()
if(require(mapproj)) {
png(file = "maps.png", width=800, height=800)
op <- par(mfrow=c(4,3), bg="gray90", oma=c(3,3,3,3), mar=c(5,4,4,2) + 0.1 )
for(yr in unique(group$year)) {
print(yr) ## This just Displays the loop running
small<-subset(group, year==yr)
data(state.fips)
party_colors <- c("#2E74C0", "#CB454A", "#FFFFFF")
small$colorBuckets <- as.numeric(as.factor(small$color))
leg.txt <- c("Democrats","Republican", "Others")
usstat.fips <- state.fips$fips[match(
map("state", plot=FALSE)$names,
state.fips$polyname)]
colorsmatched <- small$colorBuckets [match(usstat.fips,
small$state_fips)]
##MAking MAPS
par(mar=c(0,0,0,0))
map("state",
col = party_colors[colorsmatched],
fill = TRUE,
resolution = 0,
lty = 1, project = "mercator")
title(unique(small$year),
line=-2.5,cex.main=1.5)
}
title("Presidential election results by State and year",
line = 0.1,font=2, outer = TRUE, cex.main=2.5)
plot.new()
lgnd = legend("center",
leg.txt,
fill = party_colors,
ncol=1,
cex=1.8,
title = "Presidential election results \nby State and year",
# no box
bty='n')
dev.off()
par(op)
}