kanpu
kanpu

Reputation: 261

How can I get the index of the ordered data for a matrix?

The requirement is simple. For example, we can get a matrix like this:

n "matix"
> d
     [,1] [,2]
[1,]    1    3
[2,]    2    4

I want to get the index of the ordered data for the d, such as:

(2,2)
(1,2)
(2,1)
(1,1)

I think R must have a function to do this work. Any one knows that? Thank you.

Upvotes: 0

Views: 44

Answers (1)

MrFlick
MrFlick

Reputation: 206197

You can use order() to order the cells, then use arrayInd to get the indices

d<-matrix(1:4, nrow=2)
arrayInd(order(d, decreasing=T), .dim=dim(d))

#      [,1] [,2]
# [1,]    2    2
# [2,]    1    2
# [3,]    2    1
# [4,]    1    1

Upvotes: 3

Related Questions