data(iris)
x <- iris[, -5]
# Example 1: finding kNN for all points in a data matrix (using a kd-tree)
nn <- kNN(x, k = 5)
nn
# explore neighborhood of point 10
i <- 10
nn$id[i,]
plot(x, col = ifelse(1:nrow(iris) %in% nn$id[i,], "red", "black"))
# visualize the 5 nearest neighbors
plot(nn, x)
# visualize a reduced 2-NN graph
plot(kNN(nn, k = 2), x)
# Example 2: find kNN for query points
q <- x[c(1,100),]
nn <- kNN(x, k = 10, query = q)
plot(nn, x, col = "grey")
points(q, pch = 3, lwd = 2)
# Example 3: find kNN using distances
d <- dist(x, method = "manhattan")
nn <- kNN(d, k = 1)
plot(nn, x)
Run the code above in your browser using DataLab