如何向 SpatialPolygonsDataFrame 中的多边形添加孔?

How to add a hole to a polygon within a SpatialPolygonsDataFrame?

我在 SpatialPolygonsDataFrame 中有一个多边形列表,需要将其中一个设置为另一个中的孔。

我在 set_Polypath 的帮助下找到了如何在新创建的多边形上定义孔,但如何在现有多边形上设置 "hole" 标志?

看来您必须重建多边形,然后在 spdf 中替换它。

以下函数自动重建添加孔的多边形:

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)
}

然后您可以用 SpatialPolygonsDataFrame 中的两个多边形定义一个整体的多边形:

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

并得到:

然后替换spdf中的多边形

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