Sunday, March 11, 2012

Find nearest neighbours in a point cloud

From http://rwiki.sciviews.org/doku.php?id=tips:spatial-data:overlapping

library(spdep)
data(columbus)
#Extract coordinates from a data frame
coords <- columbus[,c("X", "Y")]
#For each point, determine the four closest points based on great circle distances:
knn.col <- knearneigh(as.matrix(coords), k=4, longlat=T)
knn.nb <- knn2nb(knn.col)
#What are the indices of the four nearest neighbours to point number 5?
knn.col$nn[5,]
#Equivalently:
knn.nb[[5]]
#Plot all points, then mark point number 5 by red, and its four nearest neighbours by blue:
plot(coords)
points(coords[5,], col="red", pch=19)
points(coords[knn.nb[[5]],], col="blue", pch=19)

No comments:

Post a Comment