3
$\begingroup$

I have a long table in this form:

A = {{a, 1}, {c, 2}, {b, 5}, {c, 1}, {a, 14}, {b, 7}, {b, 10}, {c, 6}, {a, 4}}  

and I want to order it by the second column, but first all with an "a" in the first element should be ordered. And then by order of appearance. It should look like this:

{{a, 1},{a, 4},{a, 14},{c, 1},{c, 2},{c, 6},{b, 5},{b, 7},{b, 10}}

SortBy[A, #[[2]] &] would sort the second column, ignoring the first.

Any ideas? Maybe a for-loop?

$\endgroup$
4
  • 2
    $\begingroup$ So, you don't want SortBy[A, {#[[1]] &, #[[2]] &}]? $\endgroup$ Mar 31, 2017 at 12:50
  • 3
    $\begingroup$ Why don't you use just Sort[A] ? $\endgroup$
    – Artes
    Mar 31, 2017 at 12:52
  • 2
    $\begingroup$ If you want it as in the OP, just try Sort /@ GatherBy[A, First]. $\endgroup$
    – Artes
    Mar 31, 2017 at 12:59
  • $\begingroup$ Thank you! Sort /@ GatherBy[A, First] was what I wanted. The other two answers would also sort the first element alphabetically. I wanted it by order of appearance. $\endgroup$
    – drcyberz
    Mar 31, 2017 at 13:34

1 Answer 1

6
$\begingroup$

From Artes' comment:

A = {{a, 1}, {c, 2}, {b, 5}, {c, 1}, {a, 14}, {b, 7}, {b, 10}, {c, 6}, {a, 4}};
Sort /@ GatherBy[A, First]

{{{a, 1}, {a, 4}, {a, 14}}, {{c, 1}, {c, 2}, {c, 6}}, {{b, 5}, {b, 7}, {b, 10}}}

$\endgroup$
2
  • 1
    $\begingroup$ To get the specified output you need to include a Flatten: Flatten[Sort /@ GatherBy[A, First], 1] $\endgroup$
    – Bob Hanlon
    Mar 31, 2017 at 16:45
  • $\begingroup$ Or Catenate instead of Flatten. $\endgroup$
    – corey979
    Mar 31, 2017 at 16:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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