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

前端 未结 1 1628
孤独总比滥情好
孤独总比滥情好 2020-12-21 15:46

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

相关标签:
1条回答
  • 2020-12-21 16:08

    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

    0 讨论(0)
提交回复
热议问题