gpt4 book ai didi

r - 合并两个 SpatialPolygonsDataFrame 对象

转载 作者:行者123 更新时间:2023-12-04 18:59:42 25 4
gpt4 key购买 nike

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

library(rgdal)
africa <- readOGR(dsn = "Data/Shapes", layer = "AfricanCountries")
class(africa)

[1] "SpatialPolygonsDataFrame" attr(,"package") [1] "sp"


我尝试了不同的软件包和解决方案,例如 raster::intersect , rgeos::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)

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

最佳答案

您可以使用 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

关于r - 合并两个 SpatialPolygonsDataFrame 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40631947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com