如何找到两个Shapefile之间的重叠?

发布于 2025-01-20 21:37:32 字数 401 浏览 4 评论 0原文

我有两个形状文件(sf),一个带有多边形,一个带有点。作为输出,我想要一个 df 显示哪些点落在哪些多边形内,如下所示:

polygon   overlap  geometry
polygon1  point34  c(3478,234872)
polygon1  point56  c(23423,234982)
polygon2  point23  c(23498,2334)
polygon3  point45  c(872348,23847)
polygon3  point87  c(234982,1237)
polygon3  point88  c(234873,2873)

我假设我必须使用 st_intersection() 做一些事情,但到目前为止我还没有设法获得所需的结果输出。

I have two shapefiles (sf), one with polygons and one with points. As output I want a df showing which points fall within which polygons, something like this:

polygon   overlap  geometry
polygon1  point34  c(3478,234872)
polygon1  point56  c(23423,234982)
polygon2  point23  c(23498,2334)
polygon3  point45  c(872348,23847)
polygon3  point87  c(234982,1237)
polygon3  point88  c(234873,2873)

I assume I'll have to do something with st_intersection() but up to now I did not manage to get the desired output.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小ぇ时光︴ 2025-01-27 21:37:32

经过一番摆弄后,我想出了这个解决方案,但我很确定它不是最优雅的。 x 和 y 是 shapefile,x 带有点,y 带有多边形。

count_overlap <- function(x, y){
  f1 <- function(z){
    r <- st_intersects(x,y[z,])
    return(r)
    }
  l1 <- c(1:nrow(y))
  l2 <- lapply(l1, f1)
  l3 <- lapply(l2, unlist)
  r <- sapply(l3, sum)
  y$overlap <- r
  return(y)
}

结果是原始 y sf/dataframe,其中添加了一个名为“重叠”的列,该列显示来自 x 的落在多边形内的点的计数。不完全是我在问题中所要求的,但对我个人来说这是一个很好的结果。

After fiddling around I came up with this solution, but I'm pretty sure it is not the most elegant. x and y are shapefiles, x with points and y with polygons.

count_overlap <- function(x, y){
  f1 <- function(z){
    r <- st_intersects(x,y[z,])
    return(r)
    }
  l1 <- c(1:nrow(y))
  l2 <- lapply(l1, f1)
  l3 <- lapply(l2, unlist)
  r <- sapply(l3, sum)
  y$overlap <- r
  return(y)
}

The result is the original y sf/dataframe with an added column called 'overlap' that shows the counts of points from x that fall within the polygon. Not exactly what I asked for in the question but a good outcome for me personally.

冷清清 2025-01-27 21:37:32

尝试在 sp:

library(sp)
out = over(pnt,plgn)

from ?over:

x = "SpatialPoints", y = "SpatialPolygons" 中使用 over
返回长度等于点数的数值向量; number 是点所在的 y 多边形的索引(编号); NA表示该点不落在多边形内;如果一个点落在多个多边形中,则记录最后一个多边形。

Try using over in sp:

library(sp)
out = over(pnt,plgn)

from ?over:

x = "SpatialPoints", y = "SpatialPolygons"
returns a numeric vector of length equal to the number of points; the number is the index (number) of the polygon of y in which a point falls; NA denotes the point does not fall in a polygon; if a point falls in multiple polygons, the last polygon is recorded.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文