I am trying to calculate the average distance between a given point and x number of its closest neighbors to understand how far points are from their neighbors for a dataset. While using earth.dist() provides the full distance matrix between all points (and global mean), I'd like to find the distance between a point and its 5 closest neighbors. For example:
frame <- data.frame(long = rnorm(100), lat = rnorm(100))
earth.dist(frame)
mean(earth.dist(frame)) # provides the global mean
Any and all help to get to the closest neighbors greatly appreciated.
To get the 5 closest neighbors for each point, you could do
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])
so the indexes of the closest neighbors for the first point are
closen[,1]
# [1] 41 26 13 75 7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With