Using the shapefile available here I am trying two merge the polygons of Sudan and South Sudan, so that I get the borders of Sudan in 2010. My code to make the shapefile available in R is
library(rgdal)
africa <- readOGR(dsn = "Data/Shapes", layer = "AfricanCountries")
class(africa)
[1] "SpatialPolygonsDataFrame" attr(,"package") [1] "sp"
I tried different packages and solutions like raster::intersect
, rgeos::gIntersect
or maptools::unionSpatialPolygons
. I always end up with a spatial object that lost the data belonging two both polygons or no union at all.
So far I have the following solution which does not seem to be very handy:
# Seperate Polygons and Data
sp_africa <- SpatialPolygons(africa@polygons, proj4string = CRS(proj4string(africa)))
dat_africa <- africa@data
# Delete South Sudan from dataframe
dat_africa <- dat_africa[-which(dat_africa$COUNTRY == "South Sudan"),]
# Add row.names to data according to polygon ID'S
rownames(dat_africa) <- dat_africa$OBJECTID
# Get all ID's
allIDs <- africa$OBJECTID
# Get the ID for Sudan, Primary Land (so we only merge the
# Sudan main land (no islands) with the South Sudan main land
sudanID <- africa[which(africa$COUNTRY == "Sudan" & africa$Land_Type == "Primary land"),]$OBJECTID
# Change ID of South Sudan to that of Sudan
allIDs[which(africa$COUNTRY == "South Sudan")] <- sudanID
# Now unite polygons and afterwards merge polygons with data
tmp <- unionSpatialPolygons(sp_africa, IDs = allIDs)
africa2 <- SpatialPolygonsDataFrame(tmp, data = dat_africa)
If there is an easier, more handy way I would be glad to know about it.