Tag Info

Hot answers tagged

13

In general SortBy can do pretty much anything that Sort does; in some cases, possibly better or faster. You can find many comparisons on this site if you just search for both function names. I also disagree with @user21382 that his task could not be expressed elegantly in SortBy form: not only can it be done, I would actually argue that it could be done ...


7

I commented on this a bit here: What are the most common pitfalls awaiting new users? Since SortBy was introduced in Mathematica 6 it is preferred where applicable over Sort with a custom comparator. This is because SortBy uses vector application of its second argument over the sort expression then the fast internal sort/ordering function, whereas Sort ...


5

SortBy is usually a more concise form of Sort, yes, but at times, you may have data that cannot be expressed, or cannot be expressed elegantly, using SortBy. For example, let's suppose that we want to sort the following by age, ascending, then by name, descending: data = { <|"Name"->"Jill", "Age" -> 23|>, <|"Name"->"Jack", "Age" -> ...


4

No one has mentioned the difference in performance: SeedRandom[0]; data = RandomInteger[{-10000, 10000}, 10^5]; sdata = Sort[data, Abs[#1] < Abs[#2] &]; // AccurateTiming sbdata = SortBy[data, Abs]; // AccurateTiming sbstable = SortBy[data, {Abs}]; // AccurateTiming (* 1.86124 0.0222057 0.00999333 *) As mentioned by MarcoB, the results are ...


2

Some options: t = Tuples[{1, 2, 3, 4, 5}, {3}]; Reverse /@ Select[t, OrderedQ] Select[t, OrderedQ] ~Reverse~ 2 Select[t, OrderedQ @* Reverse] Select[t, Reverse /* OrderedQ] Select[t, OrderedQ[#, GreaterEqual] &] 6 - Select[t, OrderedQ]


1

Ordering[{{0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0}, {0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0}, {0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0}, {1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1}, {0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0}}]//Reverse {5, 1, 2, 6, 3, 4} {{0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0}, {0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0}, ...



Only top voted, non community-wiki answers of a minimum length are eligible