R gis: identify internal boundaries between polygons with sf

This is an update of my previous similar question , the same task I need to do only within the framework sf.


I need to identify the inner borders between the polygons, the red lines on this map.

enter image description here


As part of spI used a standalone function that wrapped @Spacedman's answer . There he 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 you can use raster::boundaries().


Code for spatial data and map replication

# dev version of ggplot2 for geom_sf()
devtools::install_github("tidyverse/ggplot2")

library(tidyverse)
library(sf)

load(url("https://ikashnitsky.imtqy.com/misc/171211-so-question-identify-borders/geodata.Rdata"))

ggplot() + 
        geom_sf(data = gd_nuts0) + 
        geom_sf(data = gd_borders, color = "red") + 
        coord_sf(datum = NA) + 
        theme_void()
+4
source share
2 answers

rmapshaper uses javascript, i.e. cheating! I tried:

i = st_intersection(gd_nuts0, gd_nuts0)
i2 <- i[i$nuts_id != i$nuts_id.1,]
plot(gd_nuts0[1])
plot(i2, add = TRUE, col  ='red', lwd = 2)

enter image description here

+6
source

, rmapshaper sf - ms_innerlines(). (, ) , ms_innerlines() , sf. . . , , . , sf, - .

# dev version of ggplot2 for geom_sf()
devtools::install_github("tidyverse/ggplot2")

library(tidyverse)
library(sf)
library(rmapshaper)

load(url("https://ikashnitsky.imtqy.com/misc/171211-so-question-identify-borders/geodata.Rdata"))

sf_poly_simp <- gd_nuts0 %>% 
        ms_simplify(keep = .2, keep_shapes = TRUE) 

sf_bord_simp <- sf_poly_simp %>% 
        ms_innerlines() %>% 
        as_tibble() %>% 
        st_as_sf()

ggplot() + 
        geom_sf(data = sf_poly_simp) + 
        geom_sf(data = sf_bord_simp, color = "navy", size = 1) + 
        geom_sf(data = gd_borders, color = "red", size = .1) + 
        coord_sf(datum = NA) + 
        theme_void()

enter image description here

+5

Source: https://habr.com/ru/post/1690577/


All Articles