如何从sfc_MULTIPOLYGON提取外环并转为sfc类型?
提取sfc_MULTIPOLYGON列中多边形的外环并转为sfc格式
一步到位的简便实现
针对你混合了Polygon和MultiPolygon的几何列,无需手动处理列表,直接通过sf函数链即可完成外环提取并生成sfc_MULTIPOLYGON类型结果:
library(sf) library(data.table) # 统一几何类型为MULTIPOLYGON(避免混合类型带来的处理问题) dt[, geom := st_cast(geom, "MULTIPOLYGON")] # 提取每个几何的外环并重新组合为MULTIPOLYGON dt[, outer_rings := st_sfc(lapply(geom, function(g) { # 将MULTIPOLYGON拆分为单个Polygon individual_polys <- st_cast(g, "POLYGON") # 提取每个Polygon的外环(返回LINESTRING类型) outer_line_rings <- st_exterior_ring(individual_polys) # 将LINESTRING转为Polygon,再合并为MULTIPOLYGON st_union(st_cast(outer_line_rings, "POLYGON")) }))]
关键步骤说明
st_cast(geom, "MULTIPOLYGON"):把单列中混合的Polygon/MultiPolygon统一为MULTIPOLYGON,简化后续循环处理逻辑。st_exterior_ring():仅提取每个Polygon的外环(自动忽略孔洞对应的内环),返回LINESTRING对象。st_cast(outer_line_rings, "POLYGON"):将外环线转为多边形,才能通过st_union()合并为MULTIPOLYGON。
将已有列表转为sfc_MULTIPOLYGON
如果已经通过lapply得到了外环的列表(每个元素对应一行的外环集合),可以直接将列表转为标准sfc对象:
# 假设你已有的外环列表为ring_list,每个元素是LINESTRING或Polygon集合 dt[, outer_rings := st_sfc(lapply(ring_list, function(rings) { # 统一转为Polygon(如果原列表是LINESTRING的话) ring_polys <- if (inherits(rings[[1]], "LINESTRING")) { st_cast(rings, "POLYGON") } else { rings } # 合并为MULTIPOLYGON并返回 st_union(ring_polys) }))] # 强制统一结果类型为MULTIPOLYGON(可选,确保格式一致) dt[, outer_rings := st_cast(outer_rings, "MULTIPOLYGON")]
内容的提问来源于stack exchange,提问作者Carlos Alberto
相关产品推荐
相关产品推荐

