Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert each multilinestring to one linestring only

In this shapefile, the geometry column is linestring apart from 4 stream reaches (8168547, 8171738, 8170616 ,8169920) that are multilinestring.

enter image description here

I need to convert each multilinestring to one linestring only . I have tried many things but none worked. For example, I tried st_cast in sf package in R. However, it increased the number of the rows (it converts each multilinestring to several linestrings).

How can I convert each multilinestring to one linestring only?

like image 731
shiny Avatar asked Nov 22 '25 16:11

shiny


2 Answers

in geopandas, this can be done with explode:

import geopandas as gpd
gdf = gpd.read_file(filepath)
exploded = gdf.explode()
like image 77
Michael Delgado Avatar answered Nov 24 '25 05:11

Michael Delgado


The {sf} way of converting multilinestrings to linestrings would be, as you mention, via sf::st_cast().

But there is a problem with your data - some of the streams are not possible to make into simple linestrings. A linestring must have a single start and a single end point - this is simply not possible for some of your rchids. As a result some of your objects end up being duplicated.

As this is a general failure - and not a R specific one - I would expect the comment to be valid also for geopandas, although I have not ran the code to verify.

I suggest first casting your object to linestrings, then identifying duplicites and filtering them out.

library(sf)
library(dplyr)

streams <- st_read("tukituki_rivStrah3.shp") %>% 
  select(-length) %>% # filtering out, as length is a derived metric
  st_cast("LINESTRING")

duplicities <- streams %>% 
  st_drop_geometry() %>% 
  group_by(rchid) %>% 
  tally %>% 
  filter(n > 1) %>% 
  pull(rchid)

# this will not do...
mapview::mapview(streams[streams$rchid == duplicities[2],])

enter image description here

clean_streams <- streams %>% 
  filter(!rchid %in% duplicities)
like image 34
Jindra Lacko Avatar answered Nov 24 '25 05:11

Jindra Lacko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!