Pascal Pascal - 21 days ago 5
R Question

Dissolve holes in polygon in R

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?

Answer

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.