11
$\begingroup$

I have a list that I need to be able to assign ranks to individual elements in, giving it a number related to its position if the list were to be sorted, allowing for ties. For example, { 6, 3, 3, 6, 4, 4, 6, 4} would be transformed to { 1, 3, 3, 1, 2, 2, 1, 2} or { 3, 1, 1, 3, 2, 2, 3, 2} depending on if I were sorting for higher values or lower values.

This is for a variant on PageRank, in which after assigning each point or edge a value, the set of all edges or points is ranked, with the highest ranked point(s) getting the number 1, the second highest point(s) getting 2, and so on. I have tried using Sort and other approaches, but have not encountered anything that could be described as elegant.

$\endgroup$
12
$\begingroup$

How about:

list /. Thread[# -> Ordering@#] &@Union@list
(* {3, 1, 1, 3, 2, 2, 3, 2} *)

You can use the additional arguments of Ordering to sort it the other way:

list /. Thread[# -> Ordering[#, All, Greater]] &@Union@list
(* {1, 3, 3, 1, 2, 2, 1, 2} *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.