I have a set of polygons of which some intersect and/or touch (common borders). I am using R's sf
package to perform operations on polygons. My approach so far was to use sf::st_union()
which joins neighboring and intersecting polygons as i want, but it also combines all polygons into a MULTIPOLYGON
geometry. I would like to have each polygon separated as a sf(data.frame) class where each polygon object is show as a row in the data.frame
I show below an example. I start by creating an example dataset:
# 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)
gives:
I then perform a st_union()
operation to combine all polygon geometries that intersect or touch (the two squares above) into one:
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)
results in:
As shown above the result of df_union
is a MULTIPOLYGON
geometry with one row only. I would like to perform an operation that separates each polygon into a geometry as shown in the figure above, but resulting in several polygon objects, something equivalent to this:
# 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))
How can i do this using the sf
package?
st_cast
theMULTIPOLYGON
to aPOLYGON
– Floatable