[R-sig-Geo] Sf find number of parts in multigeometry

obrl soil obrl@oil@u @ending from gm@il@com
Tue Oct 23 06:39:43 CEST 2018


Hi Martin,

for a multipolygon geometry column, you're working with a list of
lists of lists of matrices, so you can iterate over the geometry
column like

    sapply(st_geometry(x), length)

(or purrr::map_int(), perhaps) to report number of polygon components.
To subset the first polygon component and drop the rest,

    st_geometry(x) <- st_sfc(lapply(st_geometry(x), function(y)
st_polygon(y[[1]])), crs = 4326) # or whatever crs you're using

I would first run st_buffer(x, dist = 0L) and/or
lwgeom::st_make_valid() to ensure the geometries are properly
structured, although this can't solve every problem. Note that AFAIK
there's no inherent sorting to multipolygon components, although you
could probably reorder them by area or number of vertices before
subsetting if you were really keen.

cheers
L
On Tue, Oct 23, 2018 at 12:32 PM Martin Tomko <tomkom using unimelb.edu.au> wrote:
>
> I am looking for an equivalent to Postgis ST_NumGeometries https://postgis.net/docs/ST_NumGeometries.html
> I have multipolygons in an sf df, where most of them are likely to be single part. I want to identify those that are not single part, and possibly retain only the largest polygon part, and cast all into Polygon.
> Any advice is appreciated, thanks!
>
> Martin
>
>
>         [[alternative HTML version deleted]]
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo using r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo



More information about the R-sig-Geo mailing list