0

I am trying to merge a multilinestring object to create a single linestring object and it looks like the st_line_merge function is appropriate for this purpose. However, it only seems to work when the line segments are "in order".

Consider this first code block that makes a LINESTRING:

mls1 = st_multilinestring(list(rbind(c(0,0), c(0.5, 0.7), c(1,1)), 
                              rbind(c(2,0), c(1,1)), 
                              rbind(c(2,0),c(5,0))))
st_line_merge(mls1)

Compare with this block that does not create a LINESTRING:

mls2 = st_multilinestring(list(rbind(c(0,0), c(0.5, 0.7), c(1,1)), 
                              rbind(c(2,0), c(1,1)), 
                              rbind(c(0.5,0.7),c(-1,2))))
st_line_merge(mls2)

How can I make mls2 into a LINESTRING not a MULTILINESTRING?

  • 1
    a LINESTRING is an ordered set of coordinate pairs describing a single linear chain. Your second example mls2 is three linear chains, which you can't make into a single LINESTRING - did you try plotting it? R actually merges two of your linear chains to make a MULTILINESTRING with 2 elements, which is the best it can do. What did you expect? – Spacedman Feb 27 '18 at 8:27
  • Ah, I thought the second example was doing nothing because the postgis docs say If can't be merged - original MULTILINESTRING is returned (postgis.org/docs/ST_LineMerge.html). – jsta Feb 27 '18 at 14:04
1

I was ultimately after something like this where the original geometry is cut down from 4 lines to 3:

library(sf)
lines <- st_sfc(list(st_linestring(rbind(c(0,0), c(0.5, 0.7))), 
                    st_linestring(rbind(c(0.5, 0.7), c(1, 1))), 
                    st_linestring(rbind(c(2,0), c(1,1))), 
                    st_linestring(rbind(c(1,1), c(1, 3)))))

lines_merged <- st_cast(st_line_merge(
    st_union(st_cast(lines, "MULTILINESTRING"))), "LINESTRING")

lines
lines_merged

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.