zinon
zinon

Reputation: 4664

Find points of vector that have min euclidean distance in R

In R I have two vectors

a = c(25,24,25)
b = c(33,33,32,31,26)

I'm using dist() function to calculate the euclidean distance of the values of the a,b vectors.

I want to find the value of b that has minimum distance from a point in a.

Currently my code is:

 minDist = min(dist(c(a,b), method="euclidean"))

How can I find the points that have min distance?

Upvotes: 1

Views: 2320

Answers (1)

Colonel Beauvel
Colonel Beauvel

Reputation: 31161

I would rather proceed like this:

m = outer(a,b, FUN=function(x,y) (x-y)**2)

which(m==min(m), arr.ind=T)
     row col
[1,]   1   5
[2,]   3   5

Stating that element 5 in b is the closest to element 1 and 3 in a.

Indeed:

#> m
#     [,1] [,2] [,3] [,4] [,5]
#[1,]   64   64   49   36    1
#[2,]   81   81   64   49    4
#[3,]   64   64   49   36    1

Instead of outer, a fast solution would be:

nc = length(b)
nr = length(a)
m  = (matrix(a, ncol=nc, nrow=nr) - matrix(b, ncol=nc, nrow=nr, byrow=T))**2

Upvotes: 2

Related Questions