Learn R Programming

spatialEco (version 1.2-1)

knn: Plot Spatial K nearest neighbor

Description

Find K nearest neighbors for two spatial objects

Usage

knn(y, x, k = 1, d = NULL, ids = NULL, indexes = FALSE)

Arguments

y

Spatial points or polygons object or coordinates matrix

x

Spatial points or polygons object or coordinates matrix

k

Number of neighbors

d

Optional search radius

ids

Optional column of ID's in x

indexes

(FALSE/TRUE) Return row indexes of x neighbors

Value

A data.frame with row indexes (optional), rownames, ids (optional) and distance of k

See Also

nn2 for details on search algorithm

Examples

Run this code
# 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 coordinate matrices
y <- coordinates(pts)
x <- coordinates(meuse)
knn(y, x, k=2)
  
# }

Run the code above in your browser using DataLab