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.
Perhaps you can try this
> apply(A, 2, rank)
[,1] [,2]
[1,] 2.5 2
[2,] 1.0 3
[3,] 2.5 1