簡體   English   中英

R 如何合並具有多個多邊形的 shapefile 中的多邊形特征? (可重現的代碼示例)

[英]R How do I merge polygon features in a shapefile with many polygons? (reproducible code example)

如何在具有多個多邊形的 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM