-----Original Message-----
From: David Winsemius [mailto:dwinsemius at comcast.net]
Sent: Friday, January 11, 2013 4:21 PM
To: dcarlson at tamu.edu
Cc: 'eliza botto'; r-help at r-project.org
Subject: Re: [R] locating element in distance matrix
On Jan 11, 2013, at 1:51 PM, David L Carlson wrote:
If you have a dist object (created by dist()) or if you used
extract the lower triangle of the matrix, which() will not work since
matrix is now stored as a numeric vector with n(n-1)/2 elements where
the number of rows/columns. In that case you must compute the
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]))
+ }
Wouldn't it be easier to leave the distance matrix structure intact and
just make the diagonal and upper.tri positions Inf?
+ d[row(d) <= col(d)] <- Inf
+ which(d == min(d,na.rm=FALSE), arr.ind=TRUE)
+ }
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)))
dwhich(dm, which(dm==min(dm)))
-----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
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.
Thanks in advance
?which
which( distmat == min(distmat), arr.ind=TRUE)
(It's possible to have more than one match and it would be up to
to decide how to break ties.)
--
David Winsemius, MD
Alameda, CA, USA