Skip to content

Instantly share code, notes, and snippets.

Last active March 19, 2018 14:54
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save zross/857978baba866f7894cc3fbe2fa52868 to your computer and use it in GitHub Desktop.
Spatial analysis with R
# An example of spatial analysis with R that involves grabbing data
# from a PostGIS database, joining to tabular data, projecting
# simplifying and creating an interactive map.
# This data is publicly available but requires some processing
# if you want the county boundaries you can find them here:
# c
# The tabular data requires some processing but the raw data
# is here:
# If you want to learn more about processing data with the sf
# package you can go to this DataCamp course:
# Read the poverty data
pov <- readr::read_csv("data.csv")
# Make a connection to a local PostGIS database
user= "postgres",
# Read data from PostGIS to R with sf pacakge
cnty <- st_read_db(con, table = c("geo", "tl_2016_us_county"))
cnty <- mutate(cnty, geoid = paste0(statefp, countyfp))
cnty <- st_transform(cnty, crs = 2163) # project
# Original size of file
object.size(cnty) # 127 megabytes
# Simplify
cnty_simp <- st_simplify(cnty,dTolerance = 500, preserveTopology = TRUE)
# New size of file
object.size(cnty_simp) # 5 megabytes
# Link to tabular data
cnty_dat <- filter(pov, year == 2016) %>%
inner_join(cnty_simp, ., by = "geoid")
cnty_dat <- filter(cnty_dat, !substring(geoid,1,2)%in%c("02", "15"))
# Create an interactive map
mapviewOptions(legend.pos = "bottomright")
mapview::mapview(cnty_dat, zcol="pov_per",
col.regions = colorRampPalette(brewer.pal(7, "YlOrBr")),
legend = TRUE, = "Percent poverty",
lwd = 0.2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment