Find points of vector that have min euclidean distance in R -


in r have 2 vectors

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

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

i want find value of b has minimum distance point in a.

currently code is:

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

how can find points have min distance?

i rather proceed 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 element 5 in b closest element 1 , 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, fast solution be:

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

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -