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

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

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

android - How to create dynamically Fragment pager adapter -