Get cell labels of distance cell
Data:
I have a distance matrix
called mat with the following tables and values:
>mat
179 175 176 181 249
175 147.451648
176 174.527392 28.849183
181 187.166092 40.007553 16.310747
249 194.644103 49.268129 20.637011 17.118671
336 190.182183 44.613076 16.023090 13.697248 5.613544
Problem:
I would like to extract the row and column labels for the minimum value (5.613544) of the matrix.
The expected output looks something like this:
[1] 336 249
I tried to use colnames(mat)
and rownames(mat)
, but both returned NULL
.
I know that a function labels(mat)
can return labels:
[1] "179" "175" "176" "181" "249" "336"
But here I am stuck and I cannot lower my head. Maybe something easy, sorry in advance to ask this simple question. Any ideas on how to do this?
Here's my data with dput()
:
structure(c(147.451648169349, 174.527392333086, 187.166091923018,
194.644102830409, 190.182183344061, 28.849182654733, 40.007553207889,
49.2681293306533, 44.6130761331497, 16.3107466873124, 20.6370107209517,
16.0230895738958, 17.1186706020006, 13.6972482228087, 5.6135436361904
), Size = 6L, Labels = c("179", "175", "176", "181", "249", "336"
), Diag = FALSE, Upper = FALSE, method = "euclidean", class = "dist")
source to share
The field names are stored in labels(mat)
, as you can see in dput
:
labels(mat)[which(lower.tri(mat),arr.ind=TRUE)[which.min(mat),]]
# [1] 336 249
- In the distance matrix, both fields are the same, so they
dimnames
are used insteadlabels
. -
which.min
gives the vector position of the minimum value. However, itmat
is a matrix, so ... -
which(lower.tri(mat),arr.ind=TRUE)
gives a link between matrix and vector positions.
@ Alternative to David Arenburg
names(which(as.matrix(mat) == min(mat), arr.ind = TRUE)[, 1])
-
as.matrix(mat)
takeslabels
howdimnames
. These names carry over toas.matrix(mat) == min(mat)
and are saved as a resultwhich(...,arr.ind=TRUE)
. - Since the distance matrix is โโsymmetric, c
d(a,b)==d(b,a)
, we have two minima (assuming a single minimizing pair of points). We can select a couple of points by taking the column positions[,1]
, which, again, are stored onmat
originallabels
, but now in its attributenames
.
source to share