Map maker, map maker, make me a map






[Editor’s note: The following code takes a dataframe with zipcodes and a mystery variable of interest and makes it into a map. Thanks for the code, Rose, and thanks for the data, Rita!]

if(!require(zipcode)) install.packages("zipcode"); library(zipcode)
df.raw <- read.csv("StudyFiveSampleOneWaveOne_forRclub.csv")
str(df.raw)
## 'data.frame':    1192 obs. of  2 variables:
##  $ ZipCode: int  23231 85712 85281 23917 NA 84337 89104 60629 80503 43449 ...
##  $ PScore : num  3.37 4.3 2.97 3.2 2.9 ...
if(!identical(x=clean.zipcodes(df.raw$ZipCode), y=as.character(df.raw$ZipCode)) ) message("Uh-oh") #check that zip codes in df are clean
## Uh-oh
df <- df.raw
df$zip <- clean.zipcodes(df$ZipCode)
df <- na.omit(df)

data(zipcode) # reads in a dataframe with the state for each zipcode
df <- merge(df, zipcode[,c(1,3)], by="zip", all.x=T) # add a column of state abbreviations to the datafile

library(dplyr)
df.state <- df %>%
  group_by(state) %>%
  summarize(PScore=mean(PScore))

if(!require(choroplethr)) install.packages("choroplethr"); library(choroplethr)
if(!require(choroplethrMaps)) install.packages("choroplethrMaps"); library(choroplethrMaps)

data(state.regions) # reads in a dataframe with the state name and state abbreviations

df.state <- merge(df.state, state.regions[,c(1,2)], by.x="state", by.y="abb", all.x=T)

map.data = data.frame(region=df.state$region, value=df.state$PScore)
state_choropleth(map.data)
## Warning in super$initialize(map.df, user.df): Your data.frame contains the
## following regions which are not mappable: NA
## Warning in left_join_impl(x, y, by$x, by$y): joining factor and character
## vector, coercing into character vector



Comments are closed.