我想像这个简单且可复制的示例中那样,将矩阵的值从最大的值排序和转换为最小的值:

 #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)
有什么帮助吗?谢谢

最佳答案

您可以将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

关于r - 整理矩阵,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37056974/

10-12 16:40