Suppose I have a table with say two columns. How can I sort its rows based on the first column? Is it possible in latex? If I do it in another application (like MS Excel) can I import the data from my worksheet into a tabular?
I would be very happy if you suggest me a way to handle this sorting, the easier the better! BTW I looked at sorting alphanumeric listing and didn't get it at all!
[Tex/LaTex] Sorting Table Column
tables
Best Answer
I have no doubt that
datatool
is the way to go here. However, it is possible to use the code from my answer to the sorting question to do this.You need to define a new comparator that compares only the first column. This particular implementation wants something that has a top level expansion into a row. E.g., you can define a macro for each row.
The goal is to be able to write the following to get sorted rows.
In particular, the
\sortfirstcol{\rowi\rowii\rowiii}
should expand to the sorted rows. As with\sortalpha
,\sortfirstcol
is just a simple macro that expands\sort
with the comparator\sort@firstcol
as its first argument.The comparator isn't extremely complicated, but it does need to extract the first column of each argument. For that, we use a helper macro. And in keeping with the spirit of the original answer, this version is expandable.
The
\expandafter
s are going to expand the first two arguments a single time. For example, if the comparator is "called" as\sort@firstcol{\rowi}{\rowii}{...}
, then it will expand toand so
#1
will be the tokens "C ",#3
will be "A ",#5
will be\rowi
,#6
will be\rowii
, and lastly#7
will be the{...}
that is the continuation that gets passed to the comparator.From here, it's identical to
\sort@alpha
: it compares#1
and#3
, passing#5
and#6
to the continuation.Lastly, due to the representation of the rows, the
\sortend
and\sortoutput
macros should be set to just expand to their argument:The following is a complete example using the above code and the code from the previous answer.
Finally, I should point out that this representation (that is, rows as macros) isn't necessary. Due to the way
\sort
processes its arguments, one could easily write a comparator that allowed one to write the following.Perhaps I should have done that. The comparator would be slightly simpler.
Also, as implemented, a space at the beginning or end of the first column matters. One could probably deal with that too.