kNN: Finding the indices of the 'k' NNs of a given point

View source: R/NNCTFunctions.R

kNNR Documentation

Finding the indices of the k NNs of a given point

Description

Returns the indices of the k nearest neighbors of subject i given data set or IPD matrix x. Subject indices correspond to rows (i.e. rows 1:n ) if x is the data set and to rows or columns if x is the IPD matrix.

The argument is.ipd is a logical argument (default=TRUE) to determine the structure of the argument x. If TRUE, x is taken to be the inter-point distance (IPD) matrix, and if FALSE, x is taken to be the data set with rows representing the data points.

Usage

kNN(x, i, k, is.ipd = TRUE, ...)

Arguments

x

The IPD matrix (if is.ipd=TRUE) or a data set of points in matrix or data frame form where points correspond to the rows (if is.ipd = FALSEALSE).

i

index of (i.e., row number for) the subject whose NN is to be found.

k

Integer specifying the number of NNs (of subject i).

is.ipd

A logical parameter (default=TRUE). If TRUE, x is taken as the inter-point distance matrix, otherwise, x is taken as the data set with rows representing the data points.

...

are for further arguments, such as method and p, passed to the dist function.

Value

Returns the indices (i.e. row numbers) of the k NNs of subject i

Author(s)

Elvan Ceyhan

See Also

NN, NNdist and NNdist2cl

Examples

n<-20  #or try sample(1:20,1)
Y<-matrix(runif(3*n),ncol=3)
ipd<-ipd.mat(Y)
k<-sample(1:5,1)
k
NN(ipd,1)
kNN(ipd,1,k)
kNN(Y,1,k,is.ipd = FALSE)
kNN(Y,1,k,is.ipd = FALSE,method="max")

NN(ipd,5)
kNN(ipd,5,k)
kNN(Y,5,k,is.ipd = FALSE)

#1D data points
X<-as.matrix(runif(15)) # need to be entered as a matrix with one column
#(i.e., a column vector), hence X<-runif(5) would not work
ipd<-ipd.mat(X)
kNN(ipd,3,k)

#with possible ties in the data
Y<-matrix(round(runif(30)*10),ncol=3)
ny<-nrow(Y)
ipd<-ipd.mat(Y)
for (i in 1:ny)
  cat(i,":",kNN(ipd,i,k),"\n")


nnspat documentation built on Aug. 30, 2022, 9:06 a.m.