【发布时间】:2017-02-28 15:14:49
【问题描述】:
我有一组多边形,其中一些相交和/或接触(公共边界)。我正在使用 R 的 sfpackage 对多边形执行操作。到目前为止,我的方法是使用sf::st_union(),它可以根据需要连接相邻和相交的多边形,但它也将所有多边形组合成MULTIPOLYGONgeometry。我想将每个多边形分隔为 sf(data.frame) 类,其中每个多边形对象在data.frame
我在下面展示一个例子。我首先创建一个示例数据集:
# Creating four example polygons, of which two (two squares) are neighbors:
p1 <- rbind(c(0,0), c(1,0), c(3,2), c(2,4), c(1,4), c(0,0))
pol1 <-st_polygon(list(p1))
p2 <- rbind(c(3,0), c(4,0), c(4,1), c(3,1), c(3,0))
pol2 <-st_polygon(list(p2))
p3 <- rbind(c(4,0), c(4,1), c(5,1), c(5,0),c(4,0))
pol3 <-st_polygon(list(p3))
p4 <- rbind(c(3,3), c(4,2), c(4,3), c(3,3))
pol4 <-st_polygon(list(p4))
d = data.frame(some_attribute = 1:4)
d$geometry = st_sfc(pol1,pol2,pol3,pol4)
df = st_as_sf(d)
class(df)
#[1] "sf" "data.frame"
df
# Simple feature collection with 4 features and 1 field
# geometry type: POLYGON
# dimension: XY
# bbox: xmin: 0 ymin: 0 xmax: 5 ymax: 4
# epsg (SRID): NA
# proj4string: NA
# some_attribute geometry
# 1 1 POLYGON((0 0, 1 0, 3 2, 2 4...
# 2 2 POLYGON((3 0, 4 0, 4 1, 3 1...
# 3 3 POLYGON((4 0, 4 1, 5 1, 5 0...
# 4 4 POLYGON((3 3, 4 2, 4 3, 3 3))
plot(df) 给出:
然后我执行st_union() 操作将所有相交或接触的多边形几何图形(上面的两个正方形)合并为一个:
df_union <- df %>% st_union()
df_union
# Geometry set for 1 feature
# geometry type: MULTIPOLYGON
# dimension: XY
# bbox: xmin: 0 ymin: 0 xmax: 5 ymax: 4
# epsg (SRID): NA
# proj4string: NA
# MULTIPOLYGON(((3 3, 4 3, 4 2, 3 3)), ((4 0, 3 0...
plot(df_union) 结果:
如上所示,df_union 的结果是一个只有一行的MULTIPOLYGON 几何。我想执行一个操作,将每个多边形分成一个几何图形,如上图所示,但会产生几个多边形对象,相当于:
# Simple feature collection with 4 features and 1 field
# geometry type: MULTIPOLYGON
# dimension: XY
# bbox: xmin: 0 ymin: 0 xmax: 5 ymax: 4
# epsg (SRID): NA
# proj4string: NA
# some_attribute geometry
# 1 1 POLYGON((0 0, 1 0, 3 2, 2 4...
# 2 2 POLYGON((3 0, 4 0, 5 1, 5 0...
# 3 3 POLYGON((3 3, 4 2, 4 3, 3 3))
如何使用sf 包做到这一点?
【问题讨论】:
-
您只想合并那些相互接触的多边形吗?
-
是的,合并相互接触和/或相交的多边形,将每个新多边形作为“sf”“data.frame”类对象中的一行返回。
-
然后
st_castMULTIPOLYGON到POLYGON