我有一组多边形,其中一些多边形相交和/或触摸(公共边框)。我正在使用R&#39 sf
包对多边形执行操作。到目前为止,我的方法是使用sf::st_union()
来连接相邻和相交的多边形,但它也将所有多边形组合成MULTIPOLYGON
几何。我想将每个多边形分隔为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
包进行此操作?
答案 0 :(得分:8)
感谢Edzer提供答案并为我们提供了很棒的sf
包裹!
如Edzer所述,执行st_cast
会将MULTIPOLYGON
对象转换为多个POLYGON
个对象:
df_union_cast <- st_cast(df_union, "POLYGON")
df_union_cast
# Geometry set for 3 features
# geometry type: POLYGON
# dimension: XY
# bbox: xmin: 0 ymin: 0 xmax: 5 ymax: 4
# epsg (SRID): NA
# proj4string: NA
# POLYGON((3 3, 4 3, 4 2, 3 3))
# POLYGON((4 0, 3 0, 3 1, 4 1, 5 1, 5 0, 4 0))
# POLYGON((0 0, 1 4, 2 4, 3 2, 1 0, 0 0))