I am looking for the equivalent of "Convert multipart features to multiple singlepart features. Creates simple polygons and lines" in QGIS and similar in ArcGIS for R. Various analyses create multipart features (in class sf, they are in the class MULTIPOLYGON or MULTILINESTRING) when the desired output is a simple polygons or simple lines (in class sf, they are in the class POLYGON or LINESTRING)
- 1,957
- 1
- 28
- 53
2 Answers
If you are using the sf classes then you cast it from MULTIPOLYGON to POLYGON. Example using data from spData package:
ncsf = st_read(system.file("shapes/sids.shp", package = "spData")[1])
> dim(ncsf)
[1] 100 23
100 features there. Some are MULTIPOLYGON, so let's split:
> ncmp = st_cast(ncsf,"POLYGON")
Warning message:
In st_cast.sf(ncsf, "POLYGON") :
repeating attributes for all sub-geometries for which they may not be constant
And now we have:
> dim(ncmp)
[1] 108 23
more features.
The warning is just to note that if you split features then things like "population" might not be appropriate to copy across split features (but "population density" might be...)
If you are using sp classes I would say "use sf classes", and if you can't use sf classes for your work I would say "convert to sf, then split, then convert back to sp classes".
#convert sf to sp for use with other functions
ncsf_sp<-as(ncsf, "Spatial")
#convert sp to sf for use with this function
ncsf_sp<-as(ncsf_sp, "sf")
- 1,957
- 1
- 28
- 53
- 63,755
- 5
- 81
- 115
When using the sp class, there are two functions that explode multipart features into single part features.
ms_explodefromrmapshaperwhich works for multipart polygons and multipart lines but not for SpatialMultiPoints as described in the help file for feature.disaggregatefromspalso splits into single parts but I have found situations where it leads to an error (stating an rgeos error with sp feature) when the same feature converted tosfcould be split usingst_cast. While I don't understand the behaviour, I have noticed that it can be unstable.
- 1,957
- 1
- 28
- 53
lwgeom::st_make_valid()followed byst_cast()all to MULTIPOLYGON and then finallyst_cast()all to POLYGON can be the only safe method of preserving all geometries in some cases - especially when converting data that's come out of ESRI File Geodatabases. – obrl_soil Dec 11 '18 at 21:20GEOMETRYCOLLECTION(you'll find this out because you get an error message), it may be necessary to first cast toMULTIPOLYGONbefore casting toPOLYGON. This can be done in one line:st_cast(ncsf, "MULTIPOLYGON" ) %>% st_cast("POLYGON")– user3386170 Jan 25 '19 at 14:44sf::st_cast()?? – Faustin Gashakamba Mar 06 '23 at 13:37