Creating OUTSIDE_ONLY buffer around polygon using R?
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")
Hourrah !! There is a function to create only OUTSIDE buffer !! my first (working) function in R !! :)
# create basic function
outerBuffer<-function(x, dist){
buff<-buffer(x, width = dist - 1, dissolve = T)
e<-erase(buff,x)
return(e)
}
# create data
p1 = readWKT("POLYGON((2 2,-2 2,-2 -2,2 -2,2 2))")
# apply function, create only outside buffer
a2<-outerBuffer(p1)
# tradaaa ! :)
plot(a2, col = "black", main= "Outer buffer only")
(inspired from here: http://www.dummies.com/how-to/content/how-to-create-a-function-in-r.html)
And simple solution, if multiple "Doughnuts" are need (then we need to create buffer = solid polygons and then erase the smaller solid polygon from the larger one. And delete the original polygon from the last buffer = solid polygon)
# create solid polygons
multiBuffer<-sapply(1:10, function(i){
buffer(p1,width = i, dissolve = T)
})
# create doughnuts
for (i in length(multiBuffer):2) {
multiBuffer[[i]]<-erase(multiBuffer[[i]], multiBuffer[[i-1]])
}
# I still need to delete my original polygon
multiBuffer[[1]]<-erase(multiBuffer[[1]], p1)