Return end-vertices of an sf linestring
st_cast is what you are looking for.
library(sf) library(mapview) ls <- st_sfc(st_linestring(rbind(c(0,0),c(0,1))), st_linestring(rbind(c(0,0),c(10,0)))) ptns = st_cast(ls, "POINT") mapview(ls, color = "red") + ptns
You can also cast to
MULTIPOINT if you wish.
As mentioned by @Spacedman in the comments, this returns 4 points, because 2 separate linestrings with 2 vertices each are cast. If we want only 3 points, we need to set up the line to be a single linestring with 3 vertices:
ls = st_sfc(st_linestring(matrix(c(c(0,1),c(0,0),c(10,0)), ncol = 2, byrow = TRUE)))
pnts = st_cast(ls, "POINT") will result in 3 points.
If you only want the endpoints, then
st_line_sample is what you are looking for:
ptns = st_line_sample(ls, sample = 1)
sample is a numeric value between 0 and 1 (0 being the start point and 1 the endpoint).
If still of interest (or for those having the same question):
lwgeom contains the
st_endpoint functions that return respectively the source and target vertices of a linestring.