TransWikia.com

Split a polylines according to a specific point in R

Geographic Information Systems Asked by Karim Claudio on February 15, 2021

I have 2 distinct spatial objects:

  • on one hand I have a SpatialLinesDataFrame
  • on the other hand I have a SpatialPointsDataFrame

Considering one line and one point that intersects that line, I would like to split the line into two segments according to the point.

enter image description here

The point is fixed and does intersect the line, the following command from the rgeos package

gIntersects(line.shp,point.shp)

returns TRUE.

A similar question has been asked here but the answer is based on the st_split function. However, this function is no longer implemented in the latest version of the sf package (version 0.7-3).

One Answer

in your particular context, your point divides the original line in the longitude axis. Thus, you could create two other lines, each of which would have all points of the original one to the left and right of the longitude of the point of interest. A clumsy way of doing so is to filter the coordinates of the SpatialLinesDataFrame out of a data frame

library(data.table)
library(rgdal)
crs.geo <- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84") # CRS for projection

line.coords <- data.table(spdf.line@lines[[1]]@Lines[[1]]@coords) # spdf.line is your spatial line object
segment.1 <- SpatialLines(list(Lines(Line(as.matrix(line.coords[longitude<=sp.point@coords[1]])), ID = 'id')), proj4string = crs.geo)
segment.2 <- SpatialLines(list(Lines(Line(as.matrix(line.coords[longitude>sp.point@coords[1]])), ID = 'id')), proj4string = crs.geo)

# plot it:
plot(segment.1, col = 'red')
plot(segment.1, col = 'green', add=T)

Answered by Bruno Conte Leite on February 15, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP