[英]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
的技巧,用于相同数据集中的点。
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.