[R] locating element in distance matrix

David L Carlson dcarlson at tamu.edu
Fri Jan 11 22:51:29 CET 2013

```If you have a dist object (created by dist()) or if you used lower.tri(x) to
extract the lower triangle of the matrix, which() will not work since the
matrix is now stored as a numeric vector with n(n-1)/2 elements where n is
the number of rows/columns. In that case you must compute the original
row/column values from the position along the vector:

> dwhich <- function(d, indx) {
+     i <- round((1+sqrt(1+8*length(d)))/2, 0)
+     rowd <- unlist(sapply(2:i, function(x) x:i))
+     cold <- rep(1:(i-1), (i-1):1)
+     return(data.frame(indx=indx, row=rowd[indx], col=cold[indx]))
+ }
> set.seed(42)
> x <- matrix(rnorm(100), 10, 10)
> d <- dist(x)
> dm <- as.matrix(dist(x, diag=TRUE, upper=TRUE))
> dm <- dm[lower.tri(dm)]
> dwhich(d, which(d==min(d)))
indx row col
1    9  10   1
> dwhich(dm, which(dm==min(dm)))
indx row col
1    9  10   1

> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of David Winsemius
> Sent: Friday, January 11, 2013 12:37 PM
> To: eliza botto
> Cc: r-help at r-project.org
> Subject: Re: [R] locating element in distance matrix
>
>
> On Jan 11, 2013, at 9:55 AM, eliza botto wrote:
>
> >
> > Dear useRs,
> > I have a very basic question. I have a distance matrix and i skipped
> > the upper part of it deliberately.
>
> I have no idea what htat means. Code is always helpful in resolving
> ambiguities.
>
> > The distance matrix is 1000*1000.  Then i used "min" command to
> > extract the lowest value from that matrix. Now i want to know what
> > is the location of that lowest element? More precisely, the row and
> > column number of that lowest element.
>
> ?which
> which( distmat == min(distmat), arr.ind=TRUE)
>
> (It's possible to have more than one match and it would  be up to you
> to decide how to break ties.)
>
> --
>
> David Winsemius, MD
> Alameda, CA, USA
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help