merge multiple polygon in one bordered polygon

Viewed 281

I am trying to merge two polygons (departaments) of Colombia in a single polygon. My goal is to keep only the edges of both polygons but this does not happen. Below I attach the code. Thanks for any help.

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)

Plot the two polygons

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

My expected output

enter image description here

1 Answers

Apparently the problem has to do with the first shape I was using, look for another one that you download from Arcgis and it works perfectly.

Arcgis web page

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

Shapefile .zip direct download

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

Related