Skip to content

Instantly share code, notes, and snippets.

@matt-dray
Created February 26, 2019 09:26
Show Gist options
  • Save matt-dray/d99bad6592cb558bb5fb0ac4446aae56 to your computer and use it in GitHub Desktop.
Save matt-dray/d99bad6592cb558bb5fb0ac4446aae56 to your computer and use it in GitHub Desktop.
Example of a geospatial union between polygons with R's {sf} package
# Example of a geospatial union between polygons with R's {sf} package
# Combine East and West Midlands to 'Midlands'
# This example uses a GeoJSON of super-generalised clipped boundaries for England's regions:
# http://geoportal.statistics.gov.uk/datasets/regions-december-2017-super-generalised-clipped-boundaries-in-england
# (click the API dropdown on this page and copy the URL for the GeoJSON)
# Packages
library(geojsonio)
library(sf)
library(ggplot2)
# Read GeoJSON file
region_json <- geojson_read(
x = "https://opendata.arcgis.com/datasets/4fcca2a47fed4bfaa1793015a18537ac_3.geojson",
what = "sp" # spatial class
)
# Create column that's TRUE when it's the midlands
region_sf <- st_as_sf(region_json) %>% # convert to {sf} format
mutate(midlands = ifelse(rgn17nm %in% c("East Midlands", "West Midlands"), "TRUE", FALSE))
# Create {sf} object that's all regions wihtout E and W Midlands
not_midlands <- region_sf %>%
filter(midlands == FALSE) %>%
select(region = rgn17nm, geometry) # we only need the region name and geometry
# Create {sf} object that's just the E and W Midlands
midlands <- region_sf[region_sf$midlands == TRUE, ] %>%
st_union() %>% # union of the E and W Midlands polygons
st_sf() %>% # back to {sf} object
mutate(region = "Midlands") # give the new polygon a name
# Bind the two objects
regions_simplified <- rbind(not_midlands, midlands)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment