Subsetting Shapefiles With R

I have been trying to improve my GIS skills lately and have been trying to use R for as much of this process as I can. One of the tasks I frequently perform is taking a shapefile, subsetting it, and then converting to a GeoJSON. The npm module ogr2ogr is excellent for converting from a shapefile to GeoJSON, however I frequntly find myself needing to select only certain areas of a shapefile. I have been using two libraries in R to achieve this, specifically rgdal and sp.

For example, lets use the Congressional District 2012 shapefiles from the Washington State Office of Financial Management. Downloading the file, unzipping, and then loading into R with

We want to select only the districts that cover Seattle, 7 and 9 which is as simple as subsetting

seattle.only <- subset(wa.cd, CD113FP %in% c('07', '09'))

One of the nice features about GitHub gists is that you can overlay a GeoJSON file on a Google map for a quick QC check. While R accepts a variety of projection formats, Github does not and I occasionally I find I have to convert to the WGS84 datum which are easily done with

seattle.only.wgs <- spTransform(seattle.only, CRS("+proj=longlat +ellps=WGS84"))

And written out as a GeoJSON file with

writeOGR(seattle.only.wgs, dsn="seattle.only.wgs.geojson", layer="cd2012", driver="GeoJSON", check_exists = FALSE)

Occasionally I get an error about the file I am about to create not being found. This Stack Overflow answer was very helpful and now I add the check_exists = FALSE parameter every time I write out with writeOGR().