[GIS] R: sf package points to multiple lines with st_cast

rsf

I want to create multiple lines out of given points as sf objects.

If I have a number of points as

library(sf)
pts <- st_multipoint(matrix(c(10, 10, 15, 20, 30, 30), nrow = 3, byrow = TRUE), dim = "XY")

and I am using st_cast to create lines of them

lines <- st_cast(pts, "MULTILINESTRING")

I will always get one sf object with multiple segments, but what I want to get is multiple lines (two in this example).

Best Answer

I think that the sf package need to know first how you want to create the lines from your points. I mean which pair of POINT make every LINESTRING. In my example that was defined inside the lapply function. Follow the reproducible and commented code below, hope that helps:

# Load library
library(sf)

# Create points data
multipoints <- st_multipoint(matrix(c(10, 10, 15, 20, 30, 30), nrow = 3, byrow = TRUE), dim = "XY")
points <- st_cast(st_geometry(multipoints), "POINT") 

# Number of total linestrings to be created
n <- length(points) - 1

# Build linestrings
linestrings <- lapply(X = 1:n, FUN = function(x) {

  pair <- st_combine(c(points[x], points[x + 1]))
  line <- st_cast(pair, "LINESTRING")
  return(line)

})

# One MULTILINESTRING object with all the LINESTRINGS
multilinetring <- st_multilinestring(do.call("rbind", linestrings))

# Plot
plot(multipoints, pch = 19, cex = 2)
plot(multilinetring[[1]], col = "orange", lwd = 2, add = TRUE)
plot(multilinetring[[2]], col = "green", lwd = 2, add = TRUE)

fig1

Related Question