在R sf中去除多边形中的洞

21
有没有一种方法可以利用sf包从R中的多边形中删除孔洞?我对包括其他包在内的解决方案感兴趣。 这是一个具有两个孔洞的多边形示例。
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))    

这是图片:

plot(pl1, col="red")

plot(pl1, col="red")


类似这样的吗?https://gis.stackexchange.com/questions/224048/deleting-inner-holes-rings-borders-of-a-spatial-polygon-in-r - Roman Luštrik
是的,谢谢。现在,在 sf 中是否有类似的解决方案? - Duccio A
4个回答

24

很棒的解决方案!谢谢。 - nd091680
我一直在尝试找到一个替代rgeos::gUnaryUnion的方法,最后我终于弄清楚了我需要使用sf::aggregate(),然后再使用nngeo::st_remove_holes()来实现与gUnaryUnion()相同的功能(但很快会被弃用)。 - Mac471

12

根据https://github.com/r-spatial/sf/issues/609#issuecomment-357426716的回复,以下方法可能可行:

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)

该示例创建于2018年10月5日,使用reprex package(v0.2.1)


我该如何将其应用于“shapefiles”对象?(我的意思是,删除“shapefile”中的孔) - noriega
@noriega 您可以使用 sf::st_read("your_shapefile.shp") 将 sahpefile 加载到 R 中,并使用 Ibusett 建议的方法。 - Duccio A
1
由于 pl1[1] 的存在,这会创建 length(pl1)(即3)个第一个多边形的副本 - 这是有意为之吗? - jbaums
1
@jbaums 没错,那是个笔误(现已更正)。另外请注意,我必须在 pl1 上添加一个 st_geometry 调用才能使其工作(需要一个 sfc_POLYGON 对象)。 - lbusett
此外,@AF7 提供的函数看起来很不错,而且更加通用,所以我建议用户们去看一下。 - lbusett

9

sfheaders::sf_remove_holes() 也可以做到这一点。

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

1
也许smoothr包中的fill_holes()函数也可以起作用。
链接:https://strimas.com/smoothr/reference/fill_holes.html 演示:
# fill holes smaller than 1000km2
p <- jagged_polygons$geometry[5]
area_thresh <- units::set_units(1000, km^2)
p_dropped <- fill_holes(p, threshold = area_thresh)
# plot
par(mar = c(0, 0, 1, 0), mfrow = c(1, 2))
plot(p, col = "black", main = "Original")
plot(p_dropped, col = "black", main = "After fill_holes()")

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接