2

The question is straightforward. I started using dplyr but cannot come up with a solution of how to rank the values in each row. The ultimate goal would be to assign a rank to each value and for each row. I tried the following that didn't work:

mat_agg %>% rowwise() %>% mutate_each(funs(rank))

An example is:

matrix(c(1,0,0.5,0.5, 0, 1),nrow=2)

The desired outcome would be:

matrix(c(1,3,2,2, 3, 1),nrow=2)

I very much appreciate any help. Thank you!

Patrick Balada
  • 1,330
  • 1
  • 18
  • 37
  • 3
    Please show a small reproducible example and expected output for others to test your code. I would assume it to work with `?do` – akrun Mar 22 '16 at 15:38
  • 1
    Did you try `arrange`? Here is [how to make a reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5965451#5965451). – Paul Rougieux Mar 22 '16 at 15:43
  • 1
    If you're just working with a matrix rather than a data frame, you probably don't want to use dplyr (though you may if your real example is more complex) – David Robinson Mar 22 '16 at 15:55
  • Thank you for the comment. How would you solve it using dplyr on data frames? – Patrick Balada Mar 22 '16 at 15:56
  • Added a solution with `dplyr` (as you asked for it) – akrun Mar 22 '16 at 16:36

2 Answers2

6

We can use apply() in combination with rank(). We negate m to get descending order, and transpose the output to get desired structure.

t(apply(-m,1,rank))
#     [,1] [,2] [,3]
#[1,]    1    2    3
#[2,]    3    2    1
mtoto
  • 23,919
  • 4
  • 58
  • 71
3

If we are using dplyr, convert the matrix to data.frame, and use do with rowwise

library(dplyr)
data.frame(m1) %>%
         rowwise() %>% 
         do(data.frame(t(rank(-unlist(.)))))
#      X1    X2    X3
#  (dbl) (dbl) (dbl)
#1     1     2     3
#2     3     2     1
akrun
  • 874,273
  • 37
  • 540
  • 662