Function Repository Resource:

MultiColumnSort

Source Notebook

Sort by multiple columns at the same time

Contributed by: Kotaro Okazaki

ResourceFunction["MultiColumnSort"][matrix]

sorts matrix by the elements of the first column into canonical order.

ResourceFunction["MultiColumnSort"][matrix,{{column1,order1},{column2,order2},}]

sorts multiple columns by ascending or descending order at the same time. The priority of the columns to be sorted is column1,column2, ….

Details and Options

Each column of the matrix should be composed of either all numbers or all strings.
columni must be an integer in the range of the number of matrix columns.
orderi can be any of "Ascending" or "Descending".
ResourceFunction["MultiColumnSort"] takes the same options as AlphabeticSort when a column is made up of strings.

Examples

Basic Examples (3) 

A sample matrix:

In[1]:=
matrix = {{10, 80, "c"}, {10, 85, "a"}, {12, 90, "d"}, {10, 80, "b"}};
matrix // TableForm
Out[2]=

Sort the first column elements of matrix into canonical order:

In[3]:=
ResourceFunction["MultiColumnSort"][matrix] // TableForm
Out[3]=

Sort the first column first in ascending order, then the second column in descending order, and finally the third column in ascending order:

In[4]:=
ResourceFunction["MultiColumnSort"][
  matrix, {{1, "Ascending"}, {2, "Descending"}, {3, "Ascending"}}] // TableForm
Out[4]=

Options (4) 

CaseOrdering (2) 

With CaseOrdering"LowerFirst", the lowercase form of a character is sorted before its uppercase form:

In[5]:=
matrix = {{10, 80, "file 2"}, {10, 85, "File 1"}, {12, 90, "File 3"}, {10, 80, "File 2"}};
ResourceFunction["MultiColumnSort"][
  matrix, {{1, "Ascending"}, {2, "Descending"}, {3, "Ascending"}}] // TableForm
Out[6]=

With CaseOrdering"UpperFirst", the uppercase form is sorted before the lowercase form:

In[7]:=
ResourceFunction["MultiColumnSort"][
  matrix, {{1, "Ascending"}, {2, "Descending"}, {3, "Ascending"}}, CaseOrdering -> "UpperFirst"] // TableForm
Out[7]=

IgnorePunctuation (2) 

The default value of IgnorePunctuation is False:

In[8]:=
matrix = {{10, 80, "File_2"}, {10, 85, "File 1"}, {12, 90, "File 4"}, {10, 80, "File 3"}};
ResourceFunction["MultiColumnSort"][
  matrix, {{1, "Ascending"}, {2, "Descending"}, {3, "Ascending"}}] // TableForm
Out[9]=

IgnorePunctuationTrue sorts after removing all punctuation marks and whitespace:

In[10]:=
ResourceFunction["MultiColumnSort"][
  matrix, {{1, "Ascending"}, {2, "Descending"}, {3, "Ascending"}}, IgnorePunctuation -> True] // TableForm
Out[10]=

Publisher

Kotaro Okazaki

Version History

  • 1.0.0 – 08 August 2022

Related Resources

License Information