问题
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