3
$\begingroup$

I am trying to export a set of data into a file but I can not force mathematica to keep a certain width for each column. For example, when I export a table:

table={{10,2},{3,40}};
Export["file.dat",table, "Table", "FieldSeparators"->" ", Alignment->Right]

The result is:

10  2
 2 40

Mathematica automatically determines column width such that the number with largest number of digits fits in. How can I export data with arbitrary space in each column to get:

 10    2
  2   40

such that "FieldSeparators"->" " is still the same but first column has space for three digits and the second one has space for 4 digits?

$\endgroup$
1
  • $\begingroup$ Use tab as field separators. Then it is machine readable as you have only one separator and most nice text editors align your columns. $\endgroup$
    – Johu
    Commented Jun 29, 2014 at 12:10

2 Answers 2

4
$\begingroup$

One way would be to do the padding manually:

padToWidth[width_, n_] := StringJoin@PadLeft[Characters@ToString[n], width, " "]

newData = MapAt[padToWidth[4, #] &, data, {All, 1}]; (* Apply to first column *)
newData = MapAt[padToWidth[3, #] &, newData, {All, 2}]; (* Apply to second column *)
Export["data.dat", StringJoin[First@#, " ", Last@#] & /@ newData]
$\endgroup$
4
$\begingroup$
table = {{10, 2}, {3, 40}};

export = (Transpose@IntegerString@table)[[#]] /. 
 a_String :> Table[" ", {# + 2 - StringLength@a}] <> a & /@ {1, 2} // Transpose;

Export["file.dat", export, "Table"]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.