Skip to content

Instantly share code, notes, and snippets.

@defuneste
Created October 7, 2022 14:08
Show Gist options
  • Save defuneste/e6e1f05fd14b401322bb5be0cf850b02 to your computer and use it in GitHub Desktop.
Save defuneste/e6e1f05fd14b401322bb5be0cf850b02 to your computer and use it in GitHub Desktop.
splitting a line segment with regular spacing
#loading some libs
library(sf);library(lwgeom)
# a simplified example from sf help page of st_line_sample
ls = st_sfc(st_linestring(rbind(c(.1,0), c(0,0), c(0,1))), crs = 4326) |>
st_transform(3857)
# st_line_sample give you MULTIPOINT that you convert to POINT
points <- st_line_sample(ls, density = units::set_units(1, 1/km)) |>
st_cast("POINT")
# split from lwgeom
geom_coll <- st_split(ls, points)
# giving you GEOMETRYCOLLECTION that you extract
segments <- st_collection_extract(geom_coll, "LINESTRING")
# two segments with a bit more of 501 and 121 with 1003
round(st_length(segments),2) |>table()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment