Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging Two SpatialPolygonsDataFrame Objects

Tags:

r

gis

shapefile

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.

like image 256
Martin Schmelzer Avatar asked Nov 16 '16 12:11

Martin Schmelzer


1 Answers

you can use aggregate from the raster package.

nsudan <- africa[africa$COUNTRY == "Sudan",]
ssudan <- africa[africa$COUNTRY == "South Sudan",]

plot(nsudan, axes = T, ylim = c(0, 25))
plot(ssudan, add = T)

north and south sudan

sudan <- aggregate(rbind(ssudan, nsudan))
plot(sudan)

sudan

since you create a new SpatialPolygons object, it will be difficult to keep the data from all features. You probably should append the old information from nsudan

# remove Sudan and South Sudan
africa <- africa[!africa$COUNTRY %in% c("Sudan", "South Sudan"),]

# Adjust the Polygon IDs
africa <- spChFIDs(africa, as.character(africa$OBJECTID))
sudan <- spChFIDs(sudan, as.character(max(africa$OBJECTID) + 1))

library(maptools)
africaNew <- spRbind(sudan, africa)
plot(africaNew)

africa new

like image 57
loki Avatar answered Sep 21 '22 23:09

loki