Removing holes from polygons in R sf

廉价感情. 提交于 2020-12-05 07:06:41

问题


Is there a way to remove holes from a polygon in R with the package sf? I would be interested in solutions that include other packages, too. Here's an example of a polygon with two holes.

library(sf)
outer = matrix(c(0,0,10,0,10,10,0,10,0,0),ncol=2, byrow=TRUE)
hole1 = matrix(c(1,1,1,2,2,2,2,1,1,1),ncol=2, byrow=TRUE)
hole2 = matrix(c(5,5,5,6,6,6,6,5,5,5),ncol=2, byrow=TRUE)
pts = list(outer, hole1, hole2)
(pl1 = st_polygon(pts))
# POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0), (1 1, 1 2, 2 2, 2 1, 1 1),(5 5, 5 6, 6 6, 6 5, 5 5))    

Here's the figure:

plot(pl1, col="red")


回答1:


Following https://github.com/r-spatial/sf/issues/609#issuecomment-357426716, this could work:

library(sf)
outer = matrix(c(0,0,10,0,10,10,0,10,0,0),ncol=2, byrow=TRUE)
hole1 = matrix(c(1,1,1,2,2,2,2,1,1,1),ncol=2, byrow=TRUE)
hole2 = matrix(c(5,5,5,6,6,6,6,5,5,5),ncol=2, byrow=TRUE)
pts = list(outer, hole1, hole2)
pl1 = st_geometry(st_polygon(pts))

plot(pl1)

pl2 <- st_multipolygon(lapply(pl1, function(x) x[1]))
plot(pl2)

Created on 2018-10-05 by the reprex package (v0.2.1)




回答2:


Package nngeo introduced a function to do this after this question was answered by @lbusett (and references him in the description, well done).

So you can use:

nngeo::st_remove_holes(your_sf_object)

See https://rdrr.io/cran/nngeo/man/st_remove_holes.html




回答3:


sfheaders::sf_remove_holes() can also do this

sfheaders::sf_remove_holes(pl1)
POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))


来源:https://stackoverflow.com/questions/52654701/removing-holes-from-polygons-in-r-sf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!