Getting an ordered matrix

I would like to order and convert the matrix values ​​from the largest to the smallest, as in this simple and reproducible example:

#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) 

Any help? Thanks

+5
source share
3 answers

You can convert d to a coefficient and then get rid of the levels. (This means that you do not need additional packages.)

 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 suggestion using implicit conversions]: m1[] <- factor(-m) m1 # [,1] [,2] [,3] # [1,] 5 4 1 # [2,] 6 2 5 # [3,] 1 4 3 
+10
source

base rank approach:

 #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 

While base::rank does not have the ability to immediately get what you need, we can use frank (as @eddi noted), an improved and efficient version of rank in the data.table package, like this:

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

Or, if the matrix part looks ugly, just pre-select something as a matrix, a la

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

We can use 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 
+2
source

All Articles