【问题标题】:Spatial matching of big datasets大数据集的空间匹配
【发布时间】:2013-04-06 05:00:14
【问题描述】:

我有一个包含大约 100000 个点的数据集和另一个包含大约 3000 个多边形的数据集。对于每个点,我需要找到最近的多边形(空间匹配)。多边形内的点应与该多边形匹配。

计算所有对的距离是可行的,但需要的时间比必要的要长一些。是否有一个 R 包可以利用空间索引来解决这种匹配问题?

我知道 sp 包和 over 函数,但文档没有说明任何关于索引的内容。

【问题讨论】:

  • “空间索引”是什么意思?
  • @RomanLuštrik:我的意思是像 kd-tree 这样的数据结构,参见例如en.wikipedia.org/wiki/Spatial_index#Spatial_index。这种数据结构将加速在 3000 个多边形数据集中的查找。
  • rgeos 包通常是几何运算的最佳选择。我很确定它会在适当的时候使用空间索引。基于 GEOS C 库。

标签: r matching spatial spatial-index


【解决方案1】:

您可以尝试使用 rgeos 包中的 gDistance 函数来实现此目的。作为一个例子,看看下面的例子,我从这个old thread 修改了它。希望对您有所帮助。

require( rgeos )
require( sp )

# Make some polygons
grd <- GridTopology(c(1,1), c(1,1), c(10,10))
polys <- as.SpatialPolygons.GridTopology(grd)

# Make some points and label with letter ID
set.seed( 1091 )
pts = matrix( runif( 20 , 1 , 10 ) , ncol = 2 )
sp_pts <- SpatialPoints( pts )
row.names(pts) <- letters[1:10]

# Plot
plot( polys )
text( pts , labels = row.names( pts ) , col = 2 , cex = 2 )
text( coordinates(polys) , labels = row.names( polys ) , col = "#313131" , cex = 0.75 )

# Find which polygon each point is nearest
cbind( row.names( pts ) , apply( gDistance( sp_pts , polys , byid = TRUE ) , 2 , which.min ) )
#   [,1] [,2]
#1  "a"  "86"
#2  "b"  "54"
#3  "c"  "12"
#4  "d"  "13"
#5  "e"  "78"
#6  "f"  "25"
#7  "g"  "36"
#8  "h"  "62"
#9  "i"  "40"
#10 "j"  "55"

【讨论】:

  • @krlmlr 有什么帮助,或者这对于您的大型数据集来说太慢了吗?
  • 在最新的“最新”Debian 上安装 rgeos 花了一些功夫,请参阅 github.com/rundel/rgeos/issues/1。今晚稍后再试。
  • 嗯,你建议的方法仍然计算所有对的距离。我的数据需要 16 分钟——不算太慢,但仍然如此。一种解决方法是先使用gContains,然后在其余(少数)记录上使用gDistance
  • 我认为 OP 试图找到比尝试所有距离组合更聪明的东西。也许一些基于最近距离的优化匹配操作。
【解决方案2】:

我对 R 一无所知,但我将提供一种使用 PostGIS 的可能解决方案。您可能能够在 PostGIS 中加载数据并比单独使用 R 更快地处理数据。

给定两个表planet_osm_point(80k 行)和planet_osm_polygon(30k 行),以下查询在大约 30 秒内执行

create table knn as 
select 
    pt.osm_id point_osm_id, 
    poly.osm_id poly_osm_id
from planet_osm_point pt, planet_osm_polygon poly
where poly.osm_id = (
    select p2.osm_id 
    from planet_osm_polygon p2 
    order by pt.way <-> p2.way limit 1
);

结果是基于点与多边形边界框的中心点(不是多边形本身的中心点)之间的距离的近似值。再多做一些工作,这个查询就可以根据多边形本身的中心点来获取最近的多边形,尽管它不会很快执行。

【讨论】:

  • 感谢 PostGIS 代码,但如果 R​​ 具有类似的功能(尤其是 w.r.t. 运行时),我真的很感兴趣。
猜你喜欢
  • 1970-01-01
  • 2013-03-15
  • 2016-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-10
  • 1970-01-01
  • 2022-01-13
相关资源
最近更新 更多