Rita
Rita

Reputation: 45

How to find which two objects have the smallest distance from a distance matrix?

I am trying to find which two objects have the minimum euclidean distance between them in R. I have done:

D=dist(cars) D

And I get the following distance matrix:

Acura      Audi       BMW     Buick  Corvette  Chrysler     Dodge
Audi     3.1495274                                                            
BMW      2.5272253 0.8824932                                                  
Buick    2.7363507 2.1892563 1.5595952                                        
Corvette 4.0625240 2.4510262 3.0415220 4.3323665                              
Chrysler 2.3861259 1.5829112 1.3527912 1.6089444 3.0808340                    
Dodge    2.4011411 1.7289445 1.6058003 1.8883905 2.8791439 0.4580483    

Then I determined the min distance in the matrix which is:

min(D, na.rm = T)
# [1] 0.4274665

However, is there a way to retrieve the information of to which objects (row name and col name) does this value belongs to? I would expect something like "Saab" "BMW"

Upvotes: 2

Views: 129

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76402

Use which with argument arr.ind = TRUE. The row names of the return matrix are the values the question asks for.

data(mtcars)
D <- dist(mtcars)

w <- which(as.matrix(D) == min(D), arr.ind = TRUE)
rownames(w)
#[1] "Mazda RX4 Wag" "Mazda RX4"

The distances are

as.matrix(D)[w]
#[1] 0.6153251 0.6153251

Upvotes: 1

Related Questions