Reputation: 1031
I have a distance matrix in R. I want to find the row and column indices of the minimum value in the matrix, where row index is not equal to column index (so not the distance of one value to itself). How do I do it in R?
Right now I have:
which(D == min(D), arr.ind = TRUE)
which would return the indices of the minimum value in the matrix, but wouldn't exclude the distances of values to themselves.
Upvotes: 0
Views: 519
Reputation: 269586
Assuming D is symmetric and its elements are finite set the diagonal and upper (or lower) triangular part to Inf first. (If it is not symmetric just set the diagonal part to Inf: diag(D) <- Inf
.)
# test input
D <- matrix(1:25, 5)
D <- (D + t(D)) / 2
diag(D) <- 0
D[upper.tri(D, diag = TRUE)] <- Inf
which(D == min(D), arr = TRUE)
giving:
row col
[1,] 2 1
Upvotes: 1