Just to try to filter a shape file to ease plotting
I have a shape file downloaded from UK gov:
http://geoportal.statistics.gov.uk/datasets/7ff28788e1e640de8150fb8f35703f6e_1/data?geometry=-76.678%2C45.365%2C69.572%2C63.013&orderBy=lad16cd&orderByAsc=false&where=%20(UPPER(lad16cd)%20like%20%27%25E0800000%25%27%20OR%20UPPER(lad16cd)%20like%20%27%25E08000010%25%27)%20
Based on this: https://www.r-bloggers.com/r-and-gis-working-with-shapefiles/
I wrote but do not know to filter :
setwd("~/Documents/filename")
getwd() # --double confirm real data directory
#install.packages("maptools")
library(maptools)
crswgs84=CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
ukmap=readShapePoly("filename.shp",proj4string=crswgs84,verbose=TRUE)
class(ukmap)
str(ukmap@data)
str(ukmap@polygons[[1]])
ukmap@bbox
# <-- need to do some filterig
plot(ukmap) # as this will take too long and not want to plot whole UK
For example I just want "E06000001" to "E06000020".
(the filename is "Local_Authority_Districts_December_2016_Full_Extent_Boundaries_in_the_UK" not sure how to include it in the program coding quote)
You can consider to use the sf package to read the shapefile and plot the data. Filtering the sf object is the same as filtering a data frame.
library(sf)
# Read the sahpefile
ukmap <- st_read("Local_Authority_Districts_December_2016_Full_Extent_Boundaries_in_the_UK.shp")
# Subset the sf object
ukmap_sub <- ukmap[ukmap$lad16cd %in% c("E06000001", "E06000020"), ]
# Plot the boundary of ukmap_sub
plot(st_geometry(ukmap_sub))

If you prefer to work with on SpatialPolygonsDataFrame, we can use the readOGR function from the rgdal package. After that, we can subset the SpatialPolygonsDataFrame like a regular data frame.
library(maptools)
library(rgdal)
ukmap <- readOGR(dsn = getwd(), layer = "Local_Authority_Districts_December_2016_Full_Extent_Boundaries_in_the_UK")
ukmap_sub <- ukmap[ukmap$lad16cd %in% c("E06000001", "E06000020"), ]
plot(ukmap_sub)

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With