Re: Sorting by date
- To: mathgroup at smc.vnet.net
- Subject: [mg72670] Re: Sorting by date
- From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
- Date: Sun, 14 Jan 2007 05:06:53 -0500 (EST)
- Organization: The Open University, Milton Keynes, UK
- References: <eoa6ji$mi6$1@smc.vnet.net>
Clifford Martin wrote: > Hi All, > > I have a list of lists that looks like so: > > > {{3, 137.5, 13978, {2005, 2, 8}}, {3, 138.5, 12519, {2005, 1, 4}}, {3, 171.9, 15835, {2005, 4, 12}}, {3, 142.8, 17137, {2005, 11, 19}}, > {3, 161.1, 18881, {2006, 1, 18}}, {3, 108.7, 20055, {2006, 2, 28}}, {3, 157, 21498, {2006, 9, 14}}, {3, 118.1, 10891, {2004, 11, 12}}} > > The last element per vector is a date. I'd like to sort the list so that the vectors are arranged in ascending order of date, i.e. the vector containing {2004,11,12} should be first and and the vector containing {2006,9,14} should be last. Any help would be appreciated. > > Thanks > > Cliff Hi Cliff, The most efficient way to order your list should be by using the function *Ordering* [1]: "Ordering[list] gives the positions in list at which each successive element of Sort[list] appears." For instance, In[1]:= data ={{3, 137.5, 13978, {2005, 2, 8}}, {3, 138.5, 12519, {2005, 1, 4}}, {3, 171.9, 15835, {2005, 4, 12}}, {3, 142.8, 17137, {2005, 11, 19}}, {3, 161.1, 18881, {2006, 1, 18}}, {3, 108.7, 20055, {2006, 2, 28}}, {3, 157, 21498, {2006, 9, 14}}, {3, 118.1, 10891, {2004, 11, 12}}}; In[2]:= data[[Ordering[data[[All,4]]]]] Out[2]= {{3, 118.1, 10891, {2004, 11, 12}}, {3, 138.5, 12519, {2005, 1, 4}}, {3, 137.5, 13978, {2005, 2, 8}}, {3, 171.9, 15835, {2005, 4, 12}}, {3, 142.8, 17137, {2005, 11, 19}}, {3, 161.1, 18881, {2006, 1, 18}}, {3, 108.7, 20055, {2006, 2, 28}}, {3, 157, 21498, {2006, 9, 14}}} How does this work? We want to sort the main list (data in our example) according to the sublists that compose the fourth column of data. In[3]:= data[[All,4]] Out[3]= {{2005, 2, 8}, {2005, 1, 4}, {2005, 4, 12}, {2005, 11, 19}, {2006, 1, 18}, {2006, 2, 28}, {2006, 9, 14}, {2004, 11, 12}} So, we want our list sorted in ascending order, as in In[4]:= Sort[data[[All,4]]] Out[4]= {{2004, 11, 12}, {2005, 1, 4}, {2005, 2, 8}, {2005, 4, 12}, {2005, 11, 19}, {2006, 1, 18}, {2006, 2, 28}, {2006, 9, 14}} The function *Ordering* gives us a list of the position of the element as if they were sorted by the command sort above. In[5]:= Ordering[data[[All,4]]] Out[5]= {8, 2, 1, 3, 4, 5, 6, 7} Now, we just have to use this result and the function Part with our original list. Voila! Regards, Jean-Marc [1] http://documents.wolfram.com/mathematica/functions/Ordering