合并两个 SpatialPolygonsDataFrame 对象

Merging Two SpatialPolygonsDataFrame Objects

使用可用的 shapefile here 我正在尝试合并苏丹和南苏丹的多边形,以便在 2010 年获得苏丹的边界。我在 R 中使用 shapefile 的代码是

library(rgdal)
africa    <- readOGR(dsn =  "Data/Shapes", layer = "AfricanCountries")
class(africa)
[1] "SpatialPolygonsDataFrame" attr(,"package") [1] "sp"

我尝试了不同的包和解决方案,例如 raster::intersectrgeos::gIntersectmaptools::unionSpatialPolygons。我总是以一个空间对象结束,该对象丢失了属于两个多边形或根本没有并集的数据。

到目前为止,我有以下解决方案,但似乎不是很方便:

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

如果有更简单、更方便的方法,我会很高兴知道。

您可以使用 raster 包中的 aggregate

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

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

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

由于您创建了一个新的 SpatialPolygons 对象,因此很难保留所有特征的数据。您可能应该附加来自 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)