1
votes

I am beginer in R. I have two 2D matrices which contain longitude (first colum) and latitude (second colum) data. The size of the two matrices are: dim_o(93264,2), dim_m(174688,2). I would like to find the nearest neighbour point of dim_m to dim_o. I mean the reference matrix would be dim_o. I can calculate it in Matlab (MeteoLab Toolbox) with the following way:

[indAng, disAng]=MLknn(dim_o,dim_m,1, 'Norm-2 ')

I tried the knn function in R in library (class) by:

x.train=dim_o
x.test=dim_m
response_dim=dim_o
dim.knn=knn(train=x.train, test=x.test, cl=response_dim, k=1)

but I got the error:

Error in knn(train = x.train, test = x.test, cl = response_dim, k = 1) : 
'train' and 'class' have different lengths

How can I calculate the nearest neighbour coordinate points of two different size matrices in R? Thank you for your help in advance!

1

1 Answers

0
votes

For the cl argument, you need a vector that is as long as there are rows in train; you're passing a matrix which is converted to a vector twice as long. Try:

dim.knn=knn(train=x.train, test=x.test, cl=seq_len(nrow(train)), k=1)

You could also use knn1() and omit the k=1 argument. There are other packages that implement k-nearest-neighbors, such as FNN.