Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...