删除重叠的多边形

问题描述 投票:0回答:1

我有一个大的 SpatVector,其中有许多单独的多边形,其中一些多边形彼此重叠,我想删除任何重叠位置的所有多边形,留下不重叠的部分是更好的选择,但不是必需的。理想情况下,我将能够仅使用库

terra
来解决这个问题。

这是同一 SpatVector 中两个重叠多边形的小示例,其中包含与我的较大数据集包含的基本信息相同的基本信息。

library(terra)

coords1 <- matrix(c(0, 0, 4, 0, 4, 4, 0, 4, 0, 0), ncol = 2, byrow = TRUE)
coords2 <- matrix(c(2, 2, 6, 2, 6, 6, 2, 6, 2, 2), ncol = 2, byrow = TRUE)

poly1 <- vect(coords1, type = "polygons")
poly2 <- vect(coords2, type = "polygons")

spatvect <- rbind(poly1, poly2)

spatvect$ID <- c(1, 2)
spatvect$year <- c(2020, 2021)

如果我没有充分解释我的问题或目标,请告诉我,以便我更好地澄清。

r polygon spatial terra
1个回答
0
投票

使用

sf::st_difference()
,您可以将对象与自身进行比较并返回差异。这会删除所有相交的区域。

library(terra)
library(sf)
library(ggplot2)
library(tidyterra)

coords1 <- matrix(c(0, 0, 4, 0, 4, 4, 0, 4, 0, 0), ncol = 2, byrow = TRUE)
coords2 <- matrix(c(2, 2, 6, 2, 6, 6, 2, 6, 2, 2), ncol = 2, byrow = TRUE)

poly1 <- vect(coords1, type = "polygons")
poly2 <- vect(coords2, type = "polygons")

spatvect <- rbind(poly1, poly2)

spatvect$ID <- c(1, 2)
spatvect$year <- c(2020, 2021)

# Convert SpatVector to sf, get st_difference() of itself, convert back to SpatVector
spatvect1 <- st_as_sf(spatvect) %>%
  st_difference(., .) %>%
  vect()

# Plot
ggplot() +
  geom_spatvector(data = spatvect1, aes(fill = factor(ID)))

result

© www.soinside.com 2019 - 2024. All rights reserved.