r-spatial / lwgeom

bindings to the liblwgeom library
https://r-spatial.github.io/lwgeom/
58 stars 23 forks source link

st_split decomposes linestring into pieces when linstring has overlapping segments #70

Closed antonindanalet closed 4 months ago

antonindanalet commented 3 years ago

My goal is to split a linestring using a polygon. When the linestring is entirely in the polygon, I'm expecting st_split to return the entire linestring as output. I got an unexpected result and after digging, I found that the linestring being completely in the polygon had overlapping segments. Because of this, it is decomposed in parts.

Example:

library(sf)
library(lwgeom)

# Define the border, a polygon
four_corners <- matrix(c(0, 0, 4, 0, 4, 3, 0, 3, 0, 0), 
                       ncol=2, byrow=TRUE)
pts <- list(four_corners)
my_polygon <- st_polygon(pts)

# Define a route in the middle of the polygon, not crossing it
x_coord = c(1, 2, 2, 2, 3)
y_coord = c(1, 1, 2, 1, 1)
coordinate_matrix <- cbind(x_coord, y_coord)
one_route = st_linestring(coordinate_matrix)

# Split the routes in different subroutes cut by the border (st_split)
splitted_routes <- st_split(one_route, my_polygon)
print(length(splitted_routes))
for (parts in 1:length(splitted_routes)) {
  print(splitted_routes[parts])
}

I'm expecting length(splitted_routes) to be 1.

Is this the expected behavior of st_split? And how could I get what I'm expecting in this case? I'm confused.

The full question and thinking about this problem is available here: https://gis.stackexchange.com/questions/395751/split-a-line-by-a-polygon-why-are-internal-lines-split-in-parts-using-sf-st

edzer commented 4 months ago

Upstream problem?