# NOT RUN {
library(sp)
data(meuse)
coordinates(meuse) <- ~x+y
idx <- sample(1:nrow(meuse), 10)
pts <- meuse[idx,]
meuse <- meuse[-idx,]
meuse$IDS <- 1:nrow(meuse)
# Find 2 neighbors in meuse
( nn <- knn(pts, meuse, k=2, ids = "IDS", indexes = TRUE) )
plot(pts, pch=19, main="KNN")
points(meuse[nn[,1],], pch=19, col="red")
# Using covariates (weights)
wx = as.matrix(meuse@data[,1:3])
wy = as.matrix(pts@data[,1:3])
( nn <- knn(pts, meuse, k=2, ids = "IDS", indexes = TRUE,
weights.y=wy, weights.x=wx) )
plot(pts, pch=19, main="KNN")
points(meuse[nn[,1],], pch=19, col="red")
# Using coordinate matrices
y <- coordinates(pts)
x <- coordinates(meuse)
knn(y, x, k=2)
# }
Run the code above in your browser using DataLab