Reputation: 1672
I am running some geoprocessing tasks in R, in which I am trying to create some polygons for clipping rasters of environmental information. I am buffering somewhat complex polygons, and this leaves small subgeometries that I would like to get rid of. In ArcGIS, I think this would involve converting my polygon from multipart to singlepart (or something along those lines) and then dissolving, but I don't know how to do this in R.
Here's an example that illustrates the problem:
require(maptools)
require(rgeos)
data(wrld_simpl)
wrld_simpl[which(wrld_simpl@data$NAME=='Greece'),]->greece
proj4string(greece)<-CRS('+proj=lonlat +datum=WGS84')
gBuffer(greece,width=0.5)->buf
plot(buf)
What I really want is the outer boundary of the polygon, with nothing else inside. Any ideas?
Upvotes: 14
Views: 5192
Reputation: 94182
If you just want to get the one ring that forms the boundary of your buffer, then this:
plot(SpatialPolygons(list(Polygons(list(buf@polygons[[1]]@Polygons[[1]]),ID=1))),lwd=2)
is a very ad-hoc way of doing it (and plotting it) for your case.
What you really really want is to get all the rings with ringDir=1
, since the rest will be holes. You need all the rings because your buffer might still be two disconnected islands.
outerRings = Filter(function(f){f@ringDir==1},buf@polygons[[1]]@Polygons)
outerBounds = SpatialPolygons(list(Polygons(outerRings,ID=1)))
plot(outerBounds)
might do the trick... Try it with width=0.1
and you'll see it work with multiple islands, but still removing a hole.
Upvotes: 13
Reputation: 19454
If you want the convex hull that will fit Greece, you can use the gConvexHull
function in the rgeos
package. Note that this is not necessarily the approach to take if you are dealing with polygons with holes in them, as I thought was the case from the question's title. However, from your example, it looks like the below approach will get you where you want.
myCH <- gConvexHull(greece)
plot(myCH)
which will produce something like
And to check that everything fits,
plot(myCH)
plot(greece,add=TRUE)
Upvotes: 3