Rank A Elements of A Row and Also Elements A Column of A Matrix With R

Viewed 47
x <- cbind(a=c(11,22,44,15),
           b=c(21,12,22,19),
           c=c(35,66,12,20))
rownames(x) <- c('p', 'q', 'r', 's')
XX <- cbind(rbind(x, MIN = apply(x, 2, min)), MIN = c(apply(x, 1, min), NA))
xx

#      a  b  c  MIN
# p   11 21 35  11
# q   22 12 66  12
# r   44 22 12  12
# s   15 19 20  15
# MIN 11 12 12  NA

I want to know within the row MIN and column MIN which element is rank least, the next to the least, and the next up to the highest value just like this:

#      a   b   c  MIN  RANK
# p    11  21  35  11  1
# q    22  12  66  12  2.5
# r    44  22  12  12  2.5
# s    15  19  20  15  4
# MIN  11  12  12  NA  NA
# RANK 1   2.5 2.5 NA  NA
2 Answers

Something like this?

library(tidyverse)

x <- cbind(a=c(11,22,44,15),
           b=c(21,12,22,19),
           c=c(35,66,12,20))
rownames(x) <- c('p', 'q', 'r', 's')
XX <- cbind(rbind(x, MIN = apply(x, 2, min)), MIN = c(apply(x, 1, min), NA))

XX |> 
  as_tibble(rownames = 'row_names') |> 
  mutate(rank = rank(MIN,na.last = 'keep'))
#> # A tibble: 5 x 6
#>   row_names     a     b     c   MIN  rank
#>   <chr>     <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 p            11    21    35    11   1  
#> 2 q            22    12    66    12   2.5
#> 3 r            44    22    12    12   2.5
#> 4 s            15    19    20    15   4  
#> 5 MIN          11    12    12    NA  NA

Created on 2021-08-06 by the reprex package (v2.0.0)

We could extract the elements based on the row/column names or the index, get the rank and use rbind/cbind to add another row/column

newrow <- c(rank(XX['MIN', c('a', 'b', 'c')]), MIN = NA)
newcol <- c(rank(XX[1:(nrow(XX)-1), 'MIN']), NA, NA)
cbind(rbind(XX, RANK = newrow), RANK = newcol)

-output

      a    b    c MIN RANK
p    11 21.0 35.0  11  1.0
q    22 12.0 66.0  12  2.5
r    44 22.0 12.0  12  2.5
s    15 19.0 20.0  15  4.0
MIN  11 12.0 12.0  NA   NA
RANK  1  2.5  2.5  NA   NA
Related