我正在尝试计算给定点与其最近邻居的x个数之间的平均距离,以了解数据集与其邻居的距离。虽然使用earth.dist()
提供了所有点之间的全距离矩阵(和全局平均值),但我想找到一个点与其5个最近邻居之间的距离。例如:
frame <- data.frame(long = rnorm(100), lat = rnorm(100))
earth.dist(frame)
mean(earth.dist(frame)) # provides the global mean
任何和所有帮助到最近的邻居非常感谢。
我只是排序并取第一个的意思(除了它的自我距离):
distM <- as.matrix( fossil::earth.dist(frame))
apply( distM, 1, function(x) mean( x[order(x)][2:6] ) )
#----------
1 2 3 4 5 6 7
93.57153 56.06655 129.84690 95.13023 55.96412 70.57303 55.60863
8 9 10 11 12 13 14
111.79244 17.56394 34.10893 21.80423 20.30025 29.57373 31.13890
snipped
为了得到每个点最近的5个邻居,你可以做到
library(fossil)
set.seed(15)
frame <- data.frame(long = rnorm(100), lat = rnorm(100))
ed <- earth.dist(frame)
closen <- apply(as.matrix(ed), 1, function(x) order(x)[1:6][-1])
所以第一点的最近邻居的索引是
closen[,1]
# [1] 41 26 13 75 7
我想出了如何使用lapply()
这样做。
distM <- as.matrix( fossil::earth.dist(frame))
unlist(lapply(1:nrow(distM), function(x) mean(distM[x, order(distM[x, ])[2:6]])))