R – Creating OUTSIDE_ONLY Buffer Around Polygon

bufferpolygonr

I would like to create buffers in polygons, surrounding my original polygon. However, I want to keep only the "outside polygon", not include also original polygon. In Buffer in ArcGIS I can just set function OUTSIDE_ONLY and I have my buffer zone only (http://webhelp.esri.com/arcgisdesktop/9.3/index.cfm?TopicName=Buffer%20(Analysis)).

However I didn't find a way how to make it in R? I've tried both, {rgeos} and {raster}. I know I can delete my original polygon later ({rgeos}), but is there a way how make it happen while creating buffers?

enter image description here

# stack overflow
library(rgeos)

# create polygon
p1 = readWKT("POLYGON((2 2,-2 2,-2 -2,2 -2,2 2))")
# create two buffers - one wth {raster}, one with {rgeos},
# both covers also original polygon !
b.r<-buffer(p1, width = 1, dissolve = T)
gb.r<-gBuffer(p1, width = 0.3, byid = T)

# keep only buffer
buff<- gDifference(b.r, p1)

# how can I create OUTSIDE_ONLY polygon without gDifference inter-step???

Best Answer

There is no way to define "outside only" in gBuffer. You have to go through the additional step of turning the inner polygon to null, and for a good reason. You can use the raster::erase function to remove the internal polygon. If you really want this as part of the gBuffer function why not just write your own modification of gBuffer that adds an "outside only" argument?

Add required libraries and example data. I subset the first polygon and then use spTransfrom to account for gBuffer not accepting unprojected data.

library(raster)
library(rgeos)
library(rgdal)

p <- shapefile(system.file("external/lux.shp", package="raster"))
  p <- p[1,]
  p <- spTransform(p, CRS=CRS("+proj=merc +ellps=GRS80"))

Here we buffer the polygon and then use erase to turn the internal (original) polygon to null.

b <- gBuffer(p, width=1000, quadsegs=100)
plot(p)
  plot(b,add=TRUE)  

e <- erase(b, p)                             # using raster:erase
e <- rgeos::gDifference(b, p, byid=TRUE)     # using rgeos:gDifference
  plot(e, col="red")