Reputation: 1450
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!
Upvotes: 2
Views: 1875
Reputation: 886938
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
Upvotes: 3
Reputation: 24178
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
Upvotes: 6