This is an update of my previous similar question, the same task only I need to do it within sf
framework.
I need to identify the inner boundaries between polygons, red lines in this map.
Within sp
framework I used to utilize a self written function that wrapped @Spacedman's answer. Here it is:
identify_borders <- function(SPolyDF){
require(rgeos)
require(sp)
borders <- gDifference(
as(SPolyDF,"SpatialLines"),
as(gUnaryUnion(SPolyDF),"SpatialLines"),
byid=TRUE)
df <- data.frame(len = sapply(1:length(borders),
function(i) gLength(borders[i, ])))
rownames(df) <- sapply(1:length(borders),
function(i) borders@lines[[i]]@ID)
SLDF <- SpatialLinesDataFrame(borders, data = df)
return(SLDF)
}
Alternatively one may use raster::boundaries()
.
Code to get the spatial data and replicate the map
# dev version of ggplot2 for geom_sf()
devtools::install_github("tidyverse/ggplot2")
library(tidyverse)
library(sf)
load(url("https://ikashnitsky.github.io/share/1712-so-q-identify-borders/geodata.Rdata"))
ggplot() +
geom_sf(data = gd_nuts0) +
geom_sf(data = gd_borders, color = "red") +
coord_sf(datum = NA) +
theme_void()