Liberally borrowing from the excellent ideas of @SimonO'Hanlon
and @lukeA
, you can construct a two-liner function to do what you want. I use:
arrayInd()
to return the array indexorder()
to order the upper triangular elements- and the additional trick of setting the lower triangular matrix to
NA
, usingm[lower.tr(m)] <- NA
Try this:
whichArrayMax <- function(m, n=2){
m[lower.tri(m)] <- NA
arrayInd(order(m, decreasing=TRUE)[seq(n)], .dim=dim(m))
}
mat <- matrix( c(1,2,3,2,1,5,3,5,1) , 3 , byrow = TRUE )
mat
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 2 1 5
[3,] 3 5 1
whichArrayMax(mat, 2)
[,1] [,2]
[1,] 2 3
[2,] 1 3