Last active
December 19, 2019 17:01
-
-
Save szimmer/87b81c66480f6e885dca05ba657a3a9e to your computer and use it in GitHub Desktop.
Finding ZIP code of RTI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(tmaptools) | |
library(sf) | |
library(dplyr) | |
library(stringr) | |
library(tidycensus) | |
addresses <- c("3040 E Cornwallis Rd, Durham, NC") # This is RTI HQ | |
# Google geocodes lat/lon as 35.906156, -78.864160 | |
geocoded_addresses <- geocode_OSM(addresses, as.data.frame=TRUE) %>% | |
select(lat, lon) %>% | |
mutate(Type="OSM") %>% | |
add_row(Type="Google", lat=35.906156, lon=-78.864160) #Adding lat/lon from Google | |
# Getting zip code boundaries from tidycensus package - this requires API key | |
zipcode_geo <- get_acs("zcta", "B00001_001", cache_table = TRUE, | |
geometry=TRUE) | |
(point_geo <- st_as_sf(geocoded_addresses, | |
coords=c(x="lon", y="lat"), | |
crs=4326) %>% | |
st_transform(st_crs(zipcode_geo))) #match the crs of the point to the zip | |
# It says the ZIP code is 27703 | |
# The true zip code of RTI is 27709 | |
(my_results <- st_join(point_geo, zipcode_geo, join=st_within)) | |
# Mapping the relevant zipcodes and points using ggplot | |
library(ggplot2) | |
zipcode_geo %>% | |
filter(GEOID %in% c("27709", "27703")) %>% # Actual and coded zip codes | |
ggplot(aes(fill=GEOID)) + geom_sf() + | |
geom_sf(data=my_results) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment