[英]How to generate k-nearest neighbor matrix for spatial dataframe?
I have a spatial dataframe with about 3000 points. 我有一个大约3000点的空间数据帧。 I want to generate a matrix that provides the k (in this case 30) nearest neighbors for each point.
我想生成一个矩阵,为每个点提供k(在本例中为30)最近邻居。
I can do it using a loop but i feel that there should be an elegant and optimal way for spatial points dataframe class that i do not know of. 我可以使用循环来做到这一点,但我觉得应该有一个优雅和最佳的空间点数据帧类的方式,我不知道。
Probably the fastest is to use RANN
package - assuming you have x
and y
: 可能最快的是使用
RANN
包 - 假设你有x
和y
:
library(RANN)
m <- as.matrix(nn(data.frame(x=x, y=y, z=rep(0,length(x))), p=30)$nn.idx)
gives you a 3000 x 30 matrix of closest neighbors. 为您提供最近邻居的3000 x 30矩阵。 It is several orders of magnitude faster than a naive quadratic search.
它比天真的二次搜索快几个数量级。
Edit: Just for completeness, it doesn't matter which ANN frontend you pick, with FNN
(suggested by Spacedman) this would be 编辑:为了完整性,你选择哪个ANN前端并不重要,
FNN
(Spacedman建议)这将是
library(FNN)
m <- get.knn(data.frame(x=x, y=y), 30)$nn.index
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.