Reverse Clipping (Erasing) Techniques in R

cliperaser

A reverse clip saves only the part of your spatial object that is outside
the bounds of another object, as opposed to a regular clip which saves the
parts that are inside the other object.

Performing reverse clip in ArcMap? shows how to do it in ArcMap.

How do I do this in R?

Reproducible example (on Linux machines):

system("wget 'https://github.com/Robinlovelace/Creating-maps-in-R/archive/master.zip' -P /tmp/")
unzip("/tmp/master.zip", exdir = "/tmp/master")
uk <- readOGR("/tmp/master/Creating-maps-in-R-master/data/", "ukbord")
lnd <- readOGR("/tmp/master/Creating-maps-in-R-master/data/", "LondonBoroughs")
plot(uk)
plot(lnd, add = T, col = "black")

What I want here to do is to save all of the UK except for London. Visually, I want the black shape in the resulting image to be a hole.

enter image description here

Best Answer

Seems to be a simple application of gDifference from the rgeos package:

> require(rgeos)
> ukhole = gDifference(uk, lnd)
Warning message:
In RGEOSBinTopoFunc(spgeom1, spgeom2, byid, id, "rgeos_difference") :
  spgeom1 and spgeom2 have different proj4 strings
> plot(ukhole)

The projection warning is because the LondonBoroughs shapefile doesn't have a .prj file.

Just to make sure that's a hole and not an outline or another solid polygon:

> gArea(lnd) + gArea(ukhole) - gArea(uk)
[1] 0
Related Question