Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find row and column index of top values in a matrix

Tags:

r

matrix

The position (row and column) of the maximum value in a matrix can be found by:

ma <- matrix(1:50, nrow = 5)
which(ma == max(ma), arr.ind = TRUE)

What if we do not want just the coordinates of the maximum but those of the N highest values?

Something like:

order(ma, arr.ind = TRUE, decreasing = TRUE)[1:N] # this does not exist :(
like image 869
alberto Avatar asked Sep 21 '25 00:09

alberto


1 Answers

ma <- matrix(1:50, nrow=5)

# find the 5 largest values
x <- which(ma>=sort(ma, decreasing = T)[5], arr.ind = T)
# determine the order of the 5 largest values in decreasing order
x.order <- order(ma[x], decreasing = T)
x[x.order, ]
#      row col
# [1,]   5  10
# [2,]   4  10
# [3,]   3  10
# [4,]   2  10
# [5,]   1  10
like image 134
Ven Yao Avatar answered Sep 22 '25 14:09

Ven Yao