Merging Intersecting Lines in R

I came across a problem without a clear solution. I had lots (and lots) of line segments, which represented river stretches across GB. All I wanted to do was join together touching segments into a single line feature, essenitally giving all hydrologically-independent river systems as an output. I had no attributes to help, it was purely a spatial problem, and one I thought would be easy to solve!

But it wasn’t. There are a number of solutions that *should* work, but don’t, and a lot of suggested methods that don’t fully understand the task. I tried, and failed, with suggestions in ArcGIS, QGIS and rgeos. The most promising method was using aggregate.sf (with join=st_intersects) but alas, it was also fruitless.

mergeLines concept

This is the result I was aiming for.

I particularly wanted a solution in R, but was open to any GIS solution, but in the end had to give up and fix it myself. Please feel free to do what you wish with the resulting script – it’s on GitHub and embedded below:

Data & DOI


2 thoughts on “Merging Intersecting Lines in R

Leave a Reply

Your email address will not be published. Required fields are marked *