我们在2D平面上获得了大量的点。我们需要为每个点找到集合中最近的点。例如,假设初始集如下:
foo <- data.frame(x=c(1,2,4,4,10),y=c(1,2,4,4,10))
输出应该是这样的:
ClosesPair(foo)
2
1
4
3
3 # (could be 4 also)
有什么想法吗?
答案 0 :(得分:4)
传统方法是预处理数据 并把它放在一个数据结构中,通常是K-d tree, 其中&#34;最近点&#34;查询非常快。
nnclust
包中有一个实现。
library(nnclust)
foo <- cbind(x=c(1,2,4,4,10),y=c(1,2,4,4,10))
i <- nnfind(foo)$neighbour
plot(foo)
arrows( foo[,1], foo[,2], foo[i,1], foo[i,2] )
答案 1 :(得分:1)
这是一个例子;全部包装成一个单一的功能。您可能希望将其拆分一点以进行优化。
ClosesPair <- function(foo) {
dist <- function(i, j) {
sqrt((foo[i,1]-foo[j,1])**2 + (foo[i,2]-foo[j,2])**2)
}
foo <- as.matrix(foo)
ClosestPoint <- function(i) {
indices <- 1:nrow(foo)
indices <- indices[-i]
distances <- sapply(indices, dist, i=i, USE.NAMES=TRUE)
closest <- indices[which.min(distances)]
}
sapply(1:nrow(foo), ClosestPoint)
}
ClosesPair(foo)
# [1] 2 1 4 3 3
原因是,它不能很好地处理关系。
答案 2 :(得分:0)
使用包spatstat
。它有内置函数来完成这类工作。