1

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 line3.

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.

  • the distinct function is from dplyr, not tidyverse - do not use library(tidyverse) when you can more minimally use library(dplyr). – Spacedman Sep 4 '18 at 20:07
1

How about using the unique() function:

library(sf)

# 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))

# Only unique lines
lines2 <- st_multilinestring(unique(lines))
  • library(tidyverse) is not needed here, unique is a base R function. In general, library(tidyverse) is a bad idea since it pulls in so many packages and functions, and doing it when you really only want one or two functions from, say, dplyr is not best practice. – Spacedman Sep 4 '18 at 20:05
  • Thank you! That was careless of me to forget about unique() and I've updated the question to library(dplyr) Bad habit – B. R. Sep 4 '18 at 21:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.