Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing holes from polygons in R sf

Tags:

r

polygon

sf

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

plot(pl1, col="red")

like image 681
Duccio A Avatar asked Oct 04 '18 20:10

Duccio A


2 Answers

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

like image 97
AF7 Avatar answered Oct 01 '22 01:10

AF7


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)

like image 37
lbusett Avatar answered Oct 01 '22 01:10

lbusett