将多个多边形合并为一个有边界的多边形

时间:2021-03-22 03:04:28

标签: r polygon spatial sp

我正在尝试将哥伦比亚的两个多边形(部门)合并为一个多边形。我的目标是只保留两个多边形的边缘,但这不会发生。下面我附上代码。感谢您的帮助。

download.file("https://github.com/nebulae-co/colmaps/raw/master/data/departamentos.rda","departamentos")
load("departamentos")

library(sf)
library(dplyr)
library(rgdal)
library(mapview)

df1 = subset(x = departamentos, depto == "Bogotá, D. C.")
df2 = subset(x = departamentos, depto == "Cundinamarca")

df1@data$id <- df2@data$id <- "a"

df3 = rbind(df1, df2, makeUniqueIDs = TRUE)
plot(df3)

绘制两个多边形

enter image description here

## option 1
df_12 <- sf::st_as_sf(df3) %>%
  group_by(id) %>%
  summarise(geometry = sf::st_union(geometry)) %>%
  ungroup()

plot(as_Spatial(df_12))

## option 2
plot(raster::aggregate(df3))

## option 3
plot(rgeos::gUnaryUnion(df3))

## optiom 4
plot(st_union(st_make_valid(st_as_sf(df3))))

## option 5
plot(st_as_sf(rgeos::gBuffer(as_Spatial(st_make_valid(st_as_sf(df3))), byid=F, width=0)))

我的预期输出

enter image description here

1 个答案:

答案 0 :(得分:1)

显然问题与我使用的第一个形状有关,请查找您从 Arcgis 下载的另一个形状,它运行良好。

Arcgis 网页

<块引用>

https://hub.arcgis.com/datasets/juanespo::departamentos-1?geometry=-107.669%2C-3.045%2C-40.917%2C12.241

Shapefile .zip 直接下载

<块引用>

https://opendata.arcgis.com/datasets/2059399a41da4dc0b7683d1822194ae0_0.zip

library(sf)
library(mapview)
library(dplyr)

departamentos <- st_read("E:/Users/Rafae/Downloads/departamentos/b3c7aaf2-9439-4bb6-92e1-aa7b3c401b20202046-1-1gl30yi.xiu1.shp")
#mapview(departamentos)

Centro <- subset(x = departamentos, NOMBRE_DPT %in% c("BOGOTÁ","CUNDINAMARCA")) %>%
  st_as_sf() %>% st_make_valid() %>% st_union()

plot(Centro)

enter image description here