[GIS] Deleting inner holes/rings/borders of a spatial polygon in R

polygonrshapefile

I am relatively new to GIS. I have a shapefile with spatial polygon.

> class(Park)
[1] "SpatialPolygonsDataFrame"
attr(,"package")
[1] "sp"

I use the following code to plot my data

tm_shape(Park)+tm_borders()

enter image description here

I would like to get rid of all the holes in the middle of my polygon, e.g. to keep only the outer border.

How could I do that in R (hopefully in tmap package)?

Best Answer

Assuming this is a single feature (ie nrow(Park)==1) then the first ring of the first feature should be the outer ring. So create a new spatial object using just that ring, extracted from the original.

I read my data from a shapefile

> require(raster);require(rgeos)
> hole = shapefile("./holey.shp")

Get the first ring of the first feature:

> featureNumber=1 ; ringNumber=1
> ring = SpatialPolygons(
            list(
              Polygons(
                 list(
                   hole@polygons[[featureNumber]]@Polygons[[ringNumber]]
                  ),
               ID=1)))

Now create a new SPDF with attributes from the original and geometry from the ring:

> unholed = SpatialPolygonsDataFrame(ring,data=hole@data,match.ID=FALSE)

Check the areas of the old and new objects:

> gArea(hole)
[1] 0.9832362
> gArea(unholed)
[1] 1.105185

If you check the edits on this Q you'll see I had an earlier way of doing it that tried to replace the values in the original object, but this can easily lead to an object with components that don't match up, so instead this solution builds new geometry and a new spatial object.

Related Question