I try to find an example to estimate an average value associated to a coordinate, with K nearest neighbors. I found this very help tutorial regional smoothing.

This code can find the k nearest neighbors:

knn50 <- knn2nb(knearneigh(coords, k = 50), row.names = IDs)

Now my question is: how can we calculate simple average values (by averaging the values of the K nearest neighors)?

  • 1
    I've added the "r" tag for you.
    – Spacedman
    Sep 29, 2021 at 12:30

1 Answer 1


Let's make some sample data so people can run it. First a matrix of point coordinates:

> coords = cbind(runif(100), runif(100))

Then suppose we have A measured at each of the 100 points:

> A = runif(100)

And some ID values which we might need:

> IDs = paste0("ID-",1:100)

Then we compute the nearest neighbours (I'm doing 5 nearest for simplicity):

> knn50 <- knn2nb(knearneigh(coords, k = 5), row.names = IDs)

Each element of knn50 is a vector of the index in coords of the neighbours:

> knn50[[1]]
[1] 12 21 55 87 92

So for example we can plot all the points, plot the neighbours of point 5 in green, then point 5 itself in red:

> plot(coords)
> points(coords[knn50[[5]],],col="green",pch=19)
> points(coords[5,,drop=FALSE],col="red",pch=19)

enter image description here

Then if we want to average over some measure at each of those points, here A, we can use sapply and a function that subsets from A according to those nearest elements:

> sapply(1:length(knn50), function(N){mean(A[N])})
  [1] 0.601408386 0.914703926 0.175615202 0.077348561 0.897013793 0.846810226
  [7] 0.252454209 0.878517886 0.364757435 0.973559384 0.691319680 0.330981456
 [13] 0.728837277 0.549587225 0.196916021 0.249273689 0.649543256 0.021006986

giving the mean of A for the 5 nearest neighbours of each of the 100 points. Note the A value of the point itself isn't included.

I'm not sure why you go on to mention the Getis-Ord statistics etc - that seems a bit superfluous to asking how to use the output of a nearest neighbour function like this.

  • Thank you @Spacedman. For local G stat, I discover this smoothing technique with the mentionned article. And I try to understand how it actually "smooths" the data. I edited my question.
    – John Smith
    Sep 29, 2021 at 15:39
  • 1
    You've got two questions there now - the first one about how to use KNN to compute an average, I've answered. You should cut your second question out and make a new post with it.
    – Spacedman
    Sep 29, 2021 at 15:46
  • 1
    Thank you Spacedman, I created a new question
    – John Smith
    Sep 29, 2021 at 16:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.