Search code examples
rmatchrankradix

Finding the rank of each element of row names of a matrix in R


I have a numeric matrix of 2000 rows and 6900 columns. I am using R and I want to find the rank of each element of row names in each column.

For example; if element "A" is the biggest value in the first column, third biggest in the second column and 5th biggest value in the third column. I want to replace the value of "A" with 1,3,5 in the first 3 columns. I want to do the same for all row names and all columns. Basically, I want to find the rank of a value in each column.

Is there a way to do it? I tried rank, which, sort and order function but could not make it.

I am using (and prefer) R but Python is also okay.

Thank you in advance


Solution

  • How about this.

    Example of your data based on your description:

    set.seed(1)
    m <- matrix(sample(1:25), 5, dimnames = list(LETTERS[1:5], 1:5))
    m
    #>    1  2  3  4  5
    #> A 25 11 16  9  8
    #> B  4 14 10 15 13
    #> C  7 18  6 12 21
    #> D  1 22 19 17  3
    #> E  2  5 23 20 24
    

    Solution:

    apply(m, 2, rank)
    #>   1 2 3 4 5
    #> A 5 2 3 1 2
    #> B 3 3 2 3 3
    #> C 4 4 1 2 4
    #> D 1 5 4 4 1
    #> E 2 1 5 5 5