5
$\begingroup$

How can I numbering the elements in descending order of second elements of sublists? For example, if I have the list which is

m={{1, 5}, {2, 8}, {3, 9}, {4, 2}, {5, 9}, {6, 7}, {7, 9}, {8, 10}, {9, 5}, {10, 2}}; 

The smallest second element is 2 of {10,2} so its number is 1.
Second smallest second element is also 2 of {4,2} so its number will be 2.
The output that I want is then: {4, 6, 9, 2, 8, 5, 7, 10, 3, 1}.
How can I do this?

$\endgroup$
1
  • 1
    $\begingroup$ Please have a look at SortBy. $\endgroup$ Commented Oct 30, 2012 at 10:36

2 Answers 2

4
$\begingroup$

Why you rank {10, 2} before {4, 2} escapes me. Ignoring that:

m = {{1, 5}, {2, 8}, {3, 9}, {4, 2}, {5, 9}, {6, 7}, {7, 9}, {8, 10}, {9, 5}, {10, 2}}; m[[All, 2]] // Ordering // Ordering 
{3, 6, 7, 1, 8, 5, 9, 10, 4, 2} 

Equivalent: Nest[Ordering, m[[All, 2]], 2]

See Ordering.


If we reverse m before and after we get:

Nest[Ordering, Reverse[m][[All, 2]], 2] // Reverse 
 {4, 6, 9, 2, 8, 5, 7, 10, 3, 1} 
$\endgroup$
6
  • $\begingroup$ oh, I miss that part. If second element is same, I want to rank the sublists in ascending order of first element. Can you help me one more time please? $\endgroup$ Commented Oct 30, 2012 at 11:02
  • $\begingroup$ Sometimes, I wish they'd added an OrderingBy[] in complete analogy to SortBy[]... $\endgroup$ Commented Oct 30, 2012 at 11:07
  • $\begingroup$ @Sungjin, Ordering[{{1, 5}, {2, 8}, {3, 9}, {4, 2}, {5, 9}, {6, 7}, {7, 9}, {8, 10}, {9, 5}, {10, 2}}, All, If[Last[#1] != Last[#2], Last[#1] > Last[#2], First[#1] <= First[#2]] &] $\endgroup$ Commented Oct 30, 2012 at 11:14
  • 3
    $\begingroup$ @J.M. orderingBy[list_, f_] := Ordering[{f@#, #} & /@ list] $\endgroup$ Commented Oct 30, 2012 at 12:37
  • 1
    $\begingroup$ Two or more, use a... Nest? Dijkstra would be proud! :) $\endgroup$ Commented Oct 30, 2012 at 14:02
1
$\begingroup$

Since V 12.0 there is OrderingBy:

m = {{1, 5}, {2, 8}, {3, 9}, {4, 2}, {5, 9}, {6, 7}, {7, 9}, {8, 10}, {9, 5}, {10, 2}}; Ordering @ OrderingBy[Last] @ m 

{3, 6, 7, 1, 8, 5, 9, 10, 4, 2}

$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.