使用这里提供的shapefile ,我正在尝试两个合并苏丹和南苏丹的多边形,以便我在2010年获得苏丹的边界.我在R中提供shapefile的代码是
library(rgdal)
africa <- readOGR(dsn = "Data/Shapes", layer = "AfricanCountries")
class(africa)
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)[1] "SpatialPolygonsDataFrame" attr(,"package") [1] "sp"
我试过不同的包和解决方案raster::intersect,rgeos::gIntersect或者maptools::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)
Run Code Online (Sandbox Code Playgroud)
如果有一种更简单,更方便的方式,我会很高兴知道它.
你可以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)
Run Code Online (Sandbox Code Playgroud)
sudan <- aggregate(rbind(ssudan, nsudan))
plot(sudan)
Run Code Online (Sandbox Code Playgroud)
由于您创建了一个新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)
Run Code Online (Sandbox Code Playgroud)