简体   繁体   English

对于一个数据集中的每个点,计算到第二个数据集中最近点的距离

[英]For each point in one data set, calculate distance to nearest point in second data set

Trying to find, for each point in a SpatialPointsDataFrame , the distance to the closest point in a second SpatialPointsDataFrame (equivalent to the "nearest" tool in ArcGIS for two SpatialPointDataFrames ).试图为SpatialPointsDataFrame每个点查找到第二个SpatialPointsDataFrame最近点的距离(相当于 ArcGIS 中两个SpatialPointDataFrames的“最近”工具)。

I can do the naive implementation by calculating all pairwise distances using gDistance and taking the min ( like answer 1 here ), but I have some huge datasets and was looking for something more efficient.我可以通过使用gDistance计算所有成对距离并取min如这里的答案 1 )来完成简单的实现,但我有一些庞大的数据集并且正在寻找更有效的方法。

For example, here's a trick with knearneigh for points in same dataset .例如,这里有一个knearneigh技巧,用于相同数据集中的点

Cross-posted on r-sig-geor-sig-geo上交叉发布

The SearchTrees package offers one solution. SearchTrees包提供了一种解决方案。 Quoting from its documentation, it, "provides an implementation of the QuadTree data structure [which it] uses to implement fast k-Nearest Neighbor [...] lookups in two dimensions."引用其文档,它“提供了 QuadTree 数据结构的实现 [它] 用于在二维中实现快速 k-最近邻 [...] 查找。”

Here's how you could use it to quickly find, for each point in a SpatialPoints object b , the two nearest points in a second SpatialPoints object B以下是如何使用它为SpatialPoints对象b中的每个点快速查找第二个SpatialPoints对象B 中的两个最近点

library(sp)
library(SearchTrees)

## Example data
set.seed(1)
A <- SpatialPoints(cbind(x=rnorm(100), y=rnorm(100)))
B <- SpatialPoints(cbind(x=c(-1, 0, 1), y=c(1, 0, -1)))

## Find indices of the two nearest points in A to each of the points in B
tree <- createTree(coordinates(A))
inds <- knnLookup(tree, newdat=coordinates(B), k=2)

## Show that it worked
plot(A, pch=1, cex=1.2)
points(B, col=c("blue", "red", "green"), pch=17, cex=1.5)
## Plot two nearest neigbors
points(A[inds[1,],], pch=16, col=adjustcolor("blue", alpha=0.7))
points(A[inds[2,],], pch=16, col=adjustcolor("red", alpha=0.7))
points(A[inds[3,],], pch=16, col=adjustcolor("green", alpha=0.7))

在此处输入图片说明

从R-SIG-地理位置另一项建议是knn在函数nabor库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM