[R] Nearest neighbour in a matrix
David Winsemius
dwinsemius at comcast.net
Tue Sep 27 03:03:19 CEST 2011
On Sep 26, 2011, at 7:56 PM, Spartina wrote:
> Hello all,
>
> I am brand new to R and doing an exercise for a class. I need to
> find the
> nearest neighbour for points in the following matrix:
>
>> DistanceMatrix
> x1 x2 x3 x4 x5
> [1,] 0.000000 2.828427 1.581139 2.236068 2.000000
> [2,] 2.828427 0.000000 1.581139 4.123106 2.000000
> [3,] 1.581139 1.581139 0.000000 2.549510 2.121320
> [4,] 2.236068 4.123106 2.549510 0.000000 4.123106
> [5,] 2.000000 2.000000 2.121320 4.123106 0.000000
>
> I am not sure how to go about this as my knowledge of R functions
> and syntax
> is very basic.
If we are assuming that the rows are the points in 5-space, then you
can form the unique combinations of 1:5 with the function combn(1:5,
2) and apply it to a distance function.
> apply(combn(1:5,2), 2, function(x) crossprod(DistanceMatrix[x[1], ],
+ DistanceMatrix[x[2], ])
+ )
[1] 15.71955 14.41565 23.93925 18.23050 19.22668 18.60190 26.01096
18.80117
[9] 16.83646 18.12667
Then select the minimum with which.min().
> which.min( apply(combn(1:5,2), 2, function(x)
crossprod(DistanceMatrix[x[1], ],
+ DistanceMatrix[x[2], ]) ) )
[1] 2
> combn(1:5,2)[,2]
[1] 1 3
>
> Is there a way of going at it using the pmin function?
I cannot think of one.
> Otherwise what would
> be a simple way of going about it?
>
> Sorry for posting such a basic question! I've looked at the help
> pages and
> other forums on the web but am truly stuck here.
>
> Thanks in advance for your help...
>
> Léa
--
David Winsemius, MD
West Hartford, CT
More information about the R-help
mailing list