4

I have a list of polygons in a SpatialPolygonsDataFrame and need to set one of them as a hole in an other.

I've found in the help of set_Polypath how a hole can be defined on a newly created polygon but how to set the "hole" flag on an existing polygon?

cmbarbu
  • 4,354
  • 25
  • 45
  • Seems this question has been reposted, with a worked example, here: http://stackoverflow.com/questions/29629049/how-to-make-holes-to-be-displayed-in-a-spatialpolygons – Edzer Pebesma Apr 14 '15 at 14:39
  • @edzer pebesma it is not the same question on is about display, the other about polygons handling in general – cmbarbu Apr 14 '15 at 16:54

1 Answers1

5

It looks like you have to rebuild the polygon, and then replace it in the spdf.

The following function automatically rebuild the polygon adding a hole:

library("sp")
AddHoleToPolygon <-function(poly,hole){
    # invert the coordinates for Polygons to flag it as a hole
    coordsHole <-  hole@polygons[[1]]@Polygons[[1]]@coords
    newHole <- Polygon(coordsHole,hole=TRUE)

    # punch the hole in the main poly
    listPol <- poly@polygons[[1]]@Polygons
    listPol[[length(listPol)+1]] <- newHole
    punch <- Polygons(listPol,poly@polygons[[1]]@ID)

    # make the polygon a SpatialPolygonsDataFrame as the entry
    new <- SpatialPolygons(list(punch),proj4string=poly@proj4string)
    new <- SpatialPolygonsDataFrame(new,data=as(poly,"data.frame"))

    return(new)
}

You can then then define a polygon with a whole from two polygons in a SpatialPolygonsDataFrame:

load(url("http://spatcontrol.net/CorentinMBarbu/misc/spdf.rda"))
punchedPoly <-AddHoleToPolygon(spdf[1,],spdf[2,])

And get: visualize punched polygon

And then replace the polygon in the spdf

spdf <- rbind(punchedPoly,spdf[2,])
plot(spdf,col=c(1,2),main="New SpatialPolygonsDataFrames")

enter image description here

cmbarbu
  • 4,354
  • 25
  • 45
  • what structure have poly and hole for the function to run? I just have the coordinates of the both polygons – Henry Navarro Sep 25 '18 at 13:18
  • @cmbarbu Yours function helped me a lot! I could not do this operation by any packages I found on CRAN. Than you! – Pavlo May 06 '22 at 05:24