I want to remove duplicated/overlapping lines from a multiline layer using the
sf package in R.
The layer I have has a lot of attributes, and in many cases one line is recognized as 5 overlapping lines. I want to remove the repetitive lines so that every line is unique. It is fine to lose attributes, but I need a way to reconnect those coordinates into lines. The layer is big enough that I can't query based on conditions to remove each repetitive line.
A similar question-- https://github.com/r-spatial/sf/issues/669 --was asked regarding spatial points, and the solution requires the distinct() function from tidyverse. However, when you do that with lines, you lose the attributes necessary to reconnect coordinates as lines in the first place.
Here would be example code, where the goal would be to remove the duplicate
library(sf) library(dplyr) # Example lines (note these are taken from the sf vignette) line1 <- rbind(c(0,3),c(0,4),c(1,5),c(2,5)) line2 <- rbind(c(0.2,3), c(0.2,4), c(1,4.8), c(2,4.8)) line3 <- rbind(c(0.2,3), c(0.2,4), c(1,4.8), c(2,4.8)) # Repetitive to line2 line4 <- rbind(c(0,4.4), c(0.6,5)) # Merge together as sf object lines <- st_multilinestring(list(line1,line2,line3,line4)) # Recommended method to remove identical spatial objects using sf lines_distinct <- data.frame(st_coordinates(lines)) %>% distinct(X,Y) head(lines_distinct)
The problem here is that the object
lines_distinct just has the coordinates, I have no way to differentiate line1 from line4.
I would also accept any answer using the
sp package, but I'm trying to transition more to sf.