gis - 将小多边形与R中最大的邻居合并

标签 gis polygon r-sf terra amalgamation

我有一堆代表土地覆盖类别的多边形,但是我不需要这么多细节。我想将小多边形(即 < 150m2)与其最大的邻居合并。这类似于 ArcGIS Pro 中的“消除”或 QGIS 中的“消除选定的多边形”。此过程将重复进行,因此我想在 R 中编写脚本并节省一些时间。

我能想到的唯一方法是添加一列,指示哪些多边形小于 150 平方米,然后以某种方式将它们合并到最近的邻居。

#Packages
library(terra)
library(sf)
library(dplyr)

#Adding polygons from Terra and converting to sf
v <- vect(system.file("ex/lux.shp", package="terra"))
v <- st_as_sf(v[c(1:12)])


#Adding a column indicating which polygons are under 150m2
mutate(v, area_thresh = case_when(AREA < 150 ~ 1,
                               AREA > 150 ~ 0))

最佳答案

这是一个有趣的问题,因为您需要迭代不断变化的 shapefile 的行(当您合并较小的对象时,行数将会减少)。

对于一种可能的方法,请考虑这段代码,它构建在 {sf} 附带的众所周知且深受喜爱的 NC shapefile 之上。

请注意,我使用county_id 作为唯一标识符;合并的多边形将保留较大县的 ID。

library(sf)
library(dplyr)

# the one & only NC shapefile... as geometry only
shape <- st_read(system.file("shape/nc.shp", package="sf")) %>% 
  select(CNTY_ID)

# limit for merging - in this case median area
limit <- median(st_area(shape))

# initialize iterator
i <- 1

# iterate over rows of shapefile
while (i < nrow(shape)) {
  
  # check if area over or under limit
  if(st_area(shape[i, ]) < limit) {
    
    # find id of largest neighbor
    largest_neighbor <- shape[unlist(st_touches(shape[i, ], shape)), ] %>% 
      mutate(area = st_area(.)) %>% 
      top_n(1, area) %>% 
      pull(CNTY_ID)
    
    # merge offending shape with largest neighbor
    wrk_shape <- st_union(st_geometry(shape[i, ]), 
                          st_geometry(shape[shape$CNTY_ID == largest_neighbor, ])) %>% 
      st_make_valid() %>% 
      st_as_sf() %>% 
      mutate(CNTY_ID = largest_neighbor)
    
    # rename geometry, column to enable binding
    st_geometry(wrk_shape) = attr(shape, "sf_column")
    
    # remove offending shape and unmerged neighbor
    shape <- shape[-i, ]
    shape <- filter(shape, !CNTY_ID == largest_neighbor) 
    
    # add merged shape back in
    shape <- bind_rows(shape, wrk_shape)
    
  }
  
  # don't forget to update iterator :)
  i <- i + 1
    
}

plot(st_geometry(shape))

nc shapefile with 72 counties instead of 100

关于gis - 将小多边形与R中最大的邻居合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75989088/

相关文章:

r - 评估多个选项之间距一点的最近距离?

python - 迭代字符串以创建 Lat Long 坐标数组

javascript - 有没有办法检测多段线是否在/不在此处 map api 的道路边界内?

python - numpy:获取多边形内的索引而不创建掩码

python - 在 python 中使用 Clipper 库生成多边形偏移

JavaScript - 删除线框时三 Angular 形之间的间隙

python - 如何在 PYTHON 中仅提取列表 'member' 的一部分?

r - "sf"包 (R) 是否有一个函数可以完全合并几何图形?

r - 在R中将多边形转换为sf

r - 无法分配 geom_raster 大小向量的问题