如何在具有多个多边形的 shapefile 中合并多边形要素?
rbind 和 union 只是组合了 shapefile 特征的行,它们实际上并没有合并多边形本身。
以下示例中的所需结果:
如何获取以下带有重复 ID_2 的 shapefile 以合并到 sptemp 中的单个多边形?
下面的埃塞俄比亚 GADM 级别 2 示例具有重复的 shapefile ID_2 列的前两行(值 = 1)。我想要具有 79 个功能的 sptemp,将前两行(即 ID_2 重复的行)组合在一起。 sptemp[1,] 的图会显示当前 sptemp[1,] 和 sptemp2[2,] 的位置,而没有重复之间的边界,即多边形也合并了。
示例代码:
下载、解压并加载到埃塞俄比亚 2 级的 R GADM 文件(899kb 到工作目录):
library(curl)
library(rgdal)
curl_download("http://biogeo.ucdavis.edu/data/gadm2.8/shp/ETH_adm_shp.zip",
destfile=paste0("gadmETH.zip"),
quiet=FALSE)
unzip(paste0("gadmETH.zip"), exdir="gadmETH", overwrite=FALSE)
###Load shapefile
sptemp <- readOGR(dsn="gadmETH", layer="ETH_adm2")
前两个多边形的 ID_2 列重复
###You'll see in the first two rows ID_2 is duplicated
df.sptemp <- as.data.frame(sptemp)
View(sptemp)
###I can't just delete one because they are separate polygons
plot(sptemp[1,], col="blue")
plot(sptemp[2,], add=TRUE, col="red" )
最佳答案
备注 此方法使用 st_union
,它将所有“多多边形”组合成单个多边形。这可能不是您实际想要的结果。
如果您使用 library(sf)
而不是 sp
(它是 sp
的后继者),您可以使用 st_union
加入几何图形。
您可以在 dplyr
中执行此操作管道顺序也是。
library(sf)
sptemp <- sf::st_read(dsn = "~/Desktop/gadmETH/", layer = "ETH_adm2")
library(dplyr)
sptemp %>%
group_by(ID_2) %>%
summarise(geometry = sf::st_union(geometry)) %>%
ungroup()
# Simple feature collection with 79 features and 1 field
# geometry type: GEOMETRY
# dimension: XY
# bbox: xmin: 33.00154 ymin: 3.398823 xmax: 47.95823 ymax: 14.84548
# epsg (SRID): 4326
# proj4string: +proj=longlat +datum=WGS84 +no_defs
# # A tibble: 79 x 2
# ID_2 geometry
# <dbl> <sf_geometry [degree]>
# 1 1. POLYGON ((38.85556 8.938293...
# 2 2. POLYGON ((42.15579 12.72123...
# 3 3. POLYGON ((40.17299 14.49028...
# 4 4. POLYGON ((41.11739 10.93207...
# 5 5. POLYGON ((40.61546 12.7958,...
# 6 6. POLYGON ((40.25209 11.24655...
# 7 7. POLYGON ((36.35452 12.04507...
# 8 8. POLYGON ((40.11263 10.87277...
# 9 9. POLYGON ((37.39736 11.60206...
# 10 10. POLYGON ((38.48427 12.32812...
# # ... with 69 more rows
关于R 如何在具有多个多边形的 shapefile 中合并多边形要素? (可重现的代码示例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49354393/