# Sort the data in the given way

Consider the data

data = {{x1,y1,z1},{x2,y2,z2},{x3,y3,z3},{x4,y4,z4},{x5,y5,z5},{x6,y6,z6},...}


with N rows.

It can be divided into N/3 sets of 3 rows. I would like to sort the data in a way such that the rows inside the each set will be aligned according to the growth of y parameter. Finally, if yi = yj, then the upper row must be the one for which xi > xj.

For example, if y2 > y1 > y3 and y6 > y5 = y4, and x4 > x5, then it must be

datasorted = {{x2,y2,z2},{x1,y1,z1},{x3,y3,z3},{x6,y6,z6},{x4,y4,z4},{x5,y5,z5},...}


Could you please tell me how to do this?

• SortBy[#, {-#[] &, -#[] &}] & /@ Partition[data, n/3]? – kglr Feb 25 '19 at 23:11
• @kglr I think you meant Partition[data, 3]? But OP has added an additional requirement now. – Rohit Namjoshi Feb 25 '19 at 23:14
• @kglr : thank you! However, because of my stupidness I forgot to include additional requirement to my question before you commented... – John Taylor Feb 25 '19 at 23:14
• ReverseSort[data[[All, {2, 1, 3}]]][[All, {2, 1, 3}]]? – Henrik Schumacher Feb 25 '19 at 23:21
• @RohitNamjoshi, right.; thank you. – kglr Feb 25 '19 at 23:22

## 1 Answer

You can map SortBy[#, {-#[] &, -#[] &}] & on your partitioned data:

SeedRandom
data = RandomInteger[5, {15, 3}];
partitioned = Partition[data, 3];
MatrixForm[MatrixForm /@ partitioned, TableDirections -> Row]


$$\left( \begin{array}{ccccc} \left( \begin{array}{ccc} 4 & 2 & 4 \\ 0 & 1 & 0 \\ 0 & 2 & 0 \\ \end{array} \right) & \left( \begin{array}{ccc} 0 & 3 & 5 \\ 2 & 0 & 3 \\ 4 & 4 & 1 \\ \end{array} \right) & \left( \begin{array}{ccc} 3 & 3 & 4 \\ 1 & 4 & 2 \\ 1 & 1 & 4 \\ \end{array} \right) & \left( \begin{array}{ccc} 5 & 4 & 5 \\ 0 & 3 & 3 \\ 0 & 0 & 2 \\ \end{array} \right) & \left( \begin{array}{ccc} 3 & 1 & 1 \\ 3 & 2 & 5 \\ 1 & 1 & 4 \\ \end{array} \right) \\ \end{array} \right)$$

MatrixForm[MatrixForm /@ (SortBy[#, {-#[] &, -#[] &}] & /@ partitioned),
TableDirections -> Row]


$$\left( \begin{array}{ccccc} \left( \begin{array}{ccc} 4 & 2 & 4 \\ 0 & 2 & 0 \\ 0 & 1 & 0 \\ \end{array} \right) & \left( \begin{array}{ccc} 4 & 4 & 1 \\ 0 & 3 & 5 \\ 2 & 0 & 3 \\ \end{array} \right) & \left( \begin{array}{ccc} 1 & 4 & 2 \\ 3 & 3 & 4 \\ 1 & 1 & 4 \\ \end{array} \right) & \left( \begin{array}{ccc} 5 & 4 & 5 \\ 0 & 3 & 3 \\ 0 & 0 & 2 \\ \end{array} \right) & \left( \begin{array}{ccc} 3 & 2 & 5 \\ 3 & 1 & 1 \\ 1 & 1 & 4 \\ \end{array} \right) \\ \end{array} \right)$$