Just use c
like its a vector:
> (sfc12 = c(sfc1, sfc2))
Geometry set for 2 features
geometry type: POINT
dimension: XY
bbox: xmin: 0 ymin: 1 xmax: 1 ymax: 1
epsg (SRID): NA
proj4string: NA
POINT(0 1)
POINT(1 1)
And the length is 2:
> length(sfc12)
[1] 2
Here's a function that takes an sf
polygons object and clusters all features within a threshold distance, then merges the features. So starting with N features you end up with M<=N features:
library(sf)
library(sp)
library(rgeos)
clusterSF <- function(sfpolys, thresh){
dmat = st_distance(sfpolys)
hc = hclust(as.dist(dmat>thresh), method="single")
groups = cutree(hc, h=0.5)
d = st_sf(
geom = do.call(c,
lapply(1:max(groups), function(g){
st_union(sfpolys[groups==g,])
})
)
)
d$group = 1:nrow(d)
d
}
As an example, I'll create some circular polygons based on some points. I'll have to use sp
classes and the rgeos
package until I figure out the sf
versions. So I set a seed, then create 20 random points, make buffer polygons round them,
and convert to sf
object:
set.seed(123)
pols = st_as_sf(
gBuffer(SpatialPoints(cbind(100*runif(20),100*runif(20))), width=12, byid=TRUE)
)
plot(pols)
Now the function. I'll compute clusters within 1 unit. The function returns an sf
object with a group
column:
polcluster = clusterSF(pols, 1)
In this case its down to 5 clusters:
polcluster
Simple feature collection with 5 features and 1 field
which look like this:
plot(polcluster, col=polcluster$group)
Now I think method="single"
is the right clustering method. It should merge points such that all clusters are at least thresh distance from any other cluster...
Best Answer
If I understood correctly, given a polygon layer with N features, what you need is to generate a new set of N geometries where each geometry is the result of a union with it's neighbors.
A straightforward solution can be to use a
for
loop going over the 1:N polygons, applyingst_union
on the current set of neighbors for polygoni
in each "round", as in -Where
pol
is the original layer andgeom
is the new set of merged geometries.Here is a reproducible example using the
nc
dataset -Plot 1 shows the original layer, with a specific polygon n=25 shown in red -
Plot 2 shows the layer with the new geometries, where the new polygon n=25 is merged with its neighbors -