我有一堆代表土地覆盖类别的多边形,但是我不需要这么多细节。我想将小多边形(即 < 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))
关于gis - 将小多边形与R中最大的邻居合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75989088/