这是my previous similar question的更新,我需要在sf
框架内执行相同的任务。
我需要识别此地图中多边形,红线之间的内部边界。
在sp
框架内,我曾经使用自编的函数来包装@Spasdman的answer。这是:
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)
}
或者,可以使用raster::boundaries()
。
# 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()
答案 0 :(得分:6)
rmapshaper使用javascript,即作弊!我试过了:
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)
答案 1 :(得分:5)
事实证明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.github.io/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()