订购矩阵

时间:2016-05-05 17:42:23

标签: r

我想从最大值到最小值对矩阵的值进行排序和转换,就像这个简单且可复制的例子一样:

 #From :
 d<- c(-2,-34,25,0,13,0,25,-2,1)
 m<- matrix(d,3,3)
 m
     [,1] [,2] [,3]
[1,]   -2    0   25
[2,]  -34   13   -2
[3,]   25    0    1

# To:
m1
     [,1] [,2] [,3]
[1,]    5    4    1
[2,]    6    2    5
[3,]    1    4    3

#25: biggest number therefore -->(1)
#13: second biggest one ---> (2)
# ecc ...
#-34: the smallest one ---> (6)

有任何帮助吗?感谢

3 个答案:

答案 0 :(得分:10)

您可以将d转换为factor,然后将其删除。 (这意味着您不需要任何额外的包裹。)

m1 <- m
m1[]<-unclass(factor(d, levels = sort(unique(d), decreasing=TRUE)))
# alternative solutions from comments
# or levels=sort(-d), thanks, akrun
# or, to make it shorter: m1[] <- unclass(factor(-d))
# or, [eddi's suggestion using implicit conversions]: m1[] <- factor(-m) 
m1
#      [,1] [,2] [,3]
# [1,]    5    4    1
# [2,]    6    2    5
# [3,]    1    4    3

答案 1 :(得分:6)

base rank

的方法
#get unique values, since rank itself doesn't
#  seem to have an option that allows the 
#  ranking system you have in mind
u_m = unique(c(m))

#"merge" with match
matrix(rank(-u_m)[match(m, u_m)], nrow = 3L, ncol = 3L)
#      [,1] [,2] [,3]
# [1,]    5    4    1
# [2,]    6    2    5
# [3,]    1    4    3

虽然base::rank无法立即获得您想要的内容,但我们可以使用frank(如@eddi所述),这是rank的改进版和高效版在data.table包中,如下所示:

library(data.table)
matrix(frank(-m, ties.method = "dense"), nrow = 3L, ncol = 3L)

或者,如果矩阵部分看起来很丑,只需预先分配一些矩阵, a la

m1 = m
m1[] = frank(-m, ties.method = "dense")

答案 2 :(得分:2)

我们可以使用dense_rank

library(dplyr)
m1 <- m
m1[] <- dense_rank(-m)
m1
#    [,1] [,2] [,3]
#[1,]    5    4    1
#[2,]    6    2    5
#[3,]    1    4    3