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 :(
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With