【问题标题】:Merging two shapefiles in R在 R 中合并两个 shapefile
【发布时间】:2018-04-18 18:00:04
【问题描述】:

我有一个中级 (sul.ms) 的 shapefile,它有一个名为 MesoRegion 的独特属性

library(brazilmaps)
sul.ms <- get_brmap(geo="MesoRegion",geo.filter = list(State = 43),class="SpatialPolygonsDataFrame")
plot(sul.ms)
sul.ms@data$MesoRegion

 [1] 4301 4302 4303 4304 4305 4306 4307

我有另一个 shapefile(从here 下载)

在市一级(来自其他来源)。该文件还有一个名为ID 的独特属性。

library(rgdal)
sul.mun <- readOGR("~","Rio_Grande_do_Sul_municipalities")
plot(sul.mun)
sul.mun@data$ID # should give 497 ID

我可以将它们相互叠加,这表明每个自治市都是中观地区的一部分,如下所示:

我想创建一个表,其中一列中包含自治市ID,另一列中包含对应的MesoRegion。假设有某种方法可以使用单个 mesoregion 裁剪自治市并将 mesoregion 的名称分配给裁剪区域,那么 R 中是否有任何方法可以做到这一点。

编辑:我尝试使用函数over

library(sp)
over(sul.mun, sul.ms,returnList = T)

这样就可以了。然而,我认为一个自治市是两个中间区域的一部分存在一个问题。不知道为什么会这样。

【问题讨论】:

  • 好的。我提供了 shapefiles
  • 你的第一个 shapefile 没有属性 state.id
  • 很抱歉给您带来了困惑。我现在已经编辑了问题以消除您的疑虑。

标签: r maps shapefile sp


【解决方案1】:

这是基于“sf”函数使用的可能解决方案:

library(sf)
#convert to "sf"
sul.ms_sf  <- sf::st_as_sf(sul.ms)
sul.mun_sf <- sf::st_as_sf(sul.mun)

# find centroids of the different municipalities
centroids  <- sf::st_centroid(sul.mun_sf)

# find out to which region they belong
inters <- sf::st_intersection(sul.ms_sf, centroids) %>% 
  sf::st_set_geometry(NULL)

# re-join with the municipalities to get the additional
# "nome" column
out <- dplyr::left_join(sul.mun_sf, inters) %>% 
  sf::st_sf(sf_column_name = "geometry")
head(out)  

Simple feature collection with 6 features and 7 fields
geometry type:  POLYGON
dimension:      XY
bbox:           xmin: -56.66047 ymin: -31.95874 xmax: -51.95982 ymax: -27.53024
epsg (SRID):    NA
proj4string:    +proj=longlat +ellps=GRS80 +no_defs
    ID CD_GEOCODM  NM_MUNICIP                           nome MesoRegion State Region
1 4609    4300034     ACEGUÃ         SUDOESTE RIO-GRANDENSE       4306    43      4
2 4610    4300059 ÃGUA SANTA         NOROESTE RIO-GRANDENSE       4301    43      4
3 4611    4300109       AGUDO CENTRO OCIDENTAL RIO-GRANDENSE       4303    43      4
4 4612    4300208   AJURICABA         NOROESTE RIO-GRANDENSE       4301    43      4
5 4613    4300307     ALECRIM         NOROESTE RIO-GRANDENSE       4301    43      4
6 4614    4300406    ALEGRETE         SUDOESTE RIO-GRANDENSE       4306    43      4

plot(out["nome"])

似乎有效,除了东部的一个地区保持为“NA”。

【讨论】:

  • 北美地区是一个泻湖,所以一切都按预期工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-20
  • 2013-08-26
  • 2020-10-16
  • 2023-03-06
  • 1970-01-01
相关资源
最近更新 更多