1
votes

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"

1
which(as.matrix(D) == min(D), arr.ind = TRUE). Where does the data set cars come from?Rui Barradas
It is a file from a course that I am attending, I am not quite sure where it comes from.Rita
OK, then you can post an example with built-in data set mtcars for us to be able to reproduce the problem.Rui Barradas

1 Answers

0
votes

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