Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate average distance between point and closest neighbors in R

Tags:

r

distance

geo

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.

like image 728
coding_heart Avatar asked Dec 04 '25 17:12

coding_heart


1 Answers

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
like image 133
MrFlick Avatar answered Dec 06 '25 07:12

MrFlick