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
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:
And then replace the polygon in the spdf
spdf <- rbind(punchedPoly,spdf[2,])
plot(spdf,col=c(1,2),main="New SpatialPolygonsDataFrames")