Daniel James
Daniel James

Reputation: 1433

Elegant way to obtain order(rank) of each column of a matrix

I want each element of each column of a matrix to be ranked like one will rank a vector. For instance given that A is a matrix as defined below.

(A = matrix(c(36, 37, 33, 38, 36, 32), nrow = 3, byrow = TRUE))

How do I tell R to get the rank of each column in the matrix A as shown below?

      [,1] [,2]
[1,]   36   37
[2,]   33   38
[3,]   36   32

The rank or order is

(rank_A = matrix(c(2.5, 2, 1, 3, 2.5, 1), nrow = 3, byrow = TRUE))

      [,1] [,2]
[1,]  2.5    2
[2,]  1.0    3
[3,]  2.5    1

I could have written it as below.

(rank_A <- matrix(rank(A[ ,1]), rank(A[ ,2]), nrow = 3, byrow = FALSE))

which will give me what I want but I wan a elegant way of doing it.

Upvotes: 1

Views: 726

Answers (2)

akrun
akrun

Reputation: 887038

We may use colRanks from matrixStats

library(matrixStats)
t(colRanks(A, ties.method = 'average'))
     [,1] [,2]
[1,]  2.5    2
[2,]  1.0    3
[3,]  2.5    1

Or using dapply and frank

library(collapse)
library(data.table)
dapply(A, MARGIN = 2, FUN = frank)
     [,1] [,2]
[1,]  2.5    2
[2,]  1.0    3
[3,]  2.5    1

Upvotes: 2

ThomasIsCoding
ThomasIsCoding

Reputation: 101209

Perhaps you can try this

> apply(A, 2, rank)
     [,1] [,2]
[1,]  2.5    2
[2,]  1.0    3
[3,]  2.5    1

Upvotes: 2

Related Questions