Sf: Is there a function to reverse the order of nodes of "LINESTRING" ?

Created on 22 Jan 2020  路  8Comments  路  Source: r-spatial/sf

Supposed that I have a line with multiple nodes, i.e.:

> line1 <- st_linestring(rbind(c(0,0),c(1,1),c(1,0)))
> line1
LINESTRING (0 0, 1 1, 1 0)

Is there a function to reverse the order of the line's nodes (st_line_reverse)? such that:

> line1Reverse <- st_line_reverse(line1) #hypothetical
> line1Reverse
LINESTRING (1 0, 1 1, 0 0)

Currently my solution is to recalculate the coordinates, and reverse the matrix:

> st_linestring(st_coordinates(line1)[dim(line1)[1]:1,1:2])
LINESTRING (1 0, 1 1, 0 0)

Best Wishes.

Most helpful comment

Better to avoid lwgeom where possible and use a library that is intended for public use, IMO.

All 8 comments

No, there is no such function. There is also no need to call st_coordinates because a LINESTRING _is_ a matrix:

> st_linestring(line1[rev(seq_len(nrow(line1))),])
LINESTRING (1 0, 1 1, 0 0)

has the bonus advantage that it works for empty linestrings:

> line1 = st_linestring()
> st_linestring(line1[rev(seq_len(nrow(line1))),])
LINESTRING EMPTY

FWIW, there is a GEOSReverse function available.

Ah! Does it reverse everything it gets, including ring directions and multipoints?

It reverses lines/rings, but leaves the order of components in a collection unchanged. https://geos.osgeo.org/doxygen/classgeos_1_1geom_1_1Geometry.html#a4ee841421b0ce7a987b9b740a8a9885f

I think lwgeom does it too in the same way, but I haven't compared explicitly. Maybe one is easier to implement than the other?
http://postgis.refractions.net/documentation/postgis-doxygen/d6/d29/lwgeom_8c_2e8136916191732001b9480e072fd8cb.html#2e8136916191732001b9480e072fd8cb

Better to avoid lwgeom where possible and use a library that is intended for public use, IMO.

Good point @dbaston. I hadn't tought about it that way.

Great, thanks a lot!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

adrfantini picture adrfantini  路  4Comments

dkyleward picture dkyleward  路  4Comments

gregmacfarlane picture gregmacfarlane  路  4Comments

ekarsten picture ekarsten  路  4Comments

kendonB picture kendonB  路  4Comments