# Increase speed of reverse clip (erase) for large shapefiles in R

I would like to do a reverse clip (or erase in ArcMap) from shapefiles (polygons) then to merge the two shapefiles into a single shapefile. From this post How to 'reverse clip' (erase) in R, I tested the function gDifference from the rgeos package but it's very long (several days). How can I improve the speed or is there another way to do a reverse clip in R?

Here are some information on the two shapefiles (I kept the ArcMap terminology http://pro.arcgis.com/en/pro-app/tool-reference/analysis/erase.htm)

## Input feature
> shp1
class       : SpatialPolygonsDataFrame
features    : 61378
extent      : -74, -71.5, 45, 45.875  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=NAD83 +no_defs +ellps=GRS80 +towgs84=0,0,0
variables   : 55

## Erase feature
> shp2
class       : SpatialPolygonsDataFrame
features    : 429418
extent      : -79.53649, -61.75487, 44.99248, 50.25604  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=NAD83 +no_defs +ellps=GRS80 +towgs84=0,0,0
variables   : 4


This is how you can do that:

library(raster)
# erase
x <- shp1 -shp2
# union (append)
y <- x + shp2


But it won't be faster than gDifference (which is used under the hood --- the benefit of the method shown here is that attributes are not lost).

Perhaps this speeds things up a bit

agg <- aggregate(shp2)
x <- shp1 -agg
y <- x + shp2


You have an extremely large number of polygons. Are these transformed raster data?

• Thank you very much RobertH for your answer. No, the shapefiles are not transformed raster data. Commented Feb 4, 2016 at 15:29