合并两个SpatialPolygonsDataFrame对象

时间:2016-11-16 12:15:12

标签: r gis shapefile

使用可用的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)

如果有一种更简单,更方便的方式,我会很高兴知道它。

1 个答案:

答案 0 :(得分:5)

您可以使用aggregate包中的raster

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

因为您创建了一个新的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)

africa new