14
$\begingroup$

I feel like this is a simple task, and there may be a built in method to doing this (but I can't find it if there is). I would like to be able to take a table and convert it into a structured Dataset. Preferably, I'd like it to be generic for any number of columns and rows. Lets assume that I have a table Tbl and a list of column names Col and that Tbl and Col have the same number of columns.

Col={"ColA","ColB","ColC"};
Tbl={{1,2,3},{4,5,6},{7,8,9}};

For Interest, I might also like it to handle an optional list of row names RowNames.

RowNames={"Row1","Row2","Row3"};

Please let me know if you can come up with a simple way to do this

The final desired format would be something like this:

Result = Dataset[{<|"ColA" -> 1, "ColB" -> 2, "ColC" -> 3|>,
                  <|"ColA" -> 4, "ColB" -> 5, "ColC" -> 6|>,
                  <|"ColA" -> 7, "ColB" -> 8, "ColC" -> 9|>}]

or this if it used RowNames:

Dataset[<|"Row1" -> <|"ColA" -> 1, "ColB" -> 2, "ColC" -> 3|>,
          "Row2" -> <|"ColA" -> 4, "ColB" -> 5, "ColC" -> 6|>,
          "Row3" -> <|"ColA" -> 7, "ColB" -> 8, "ColC" -> 9|>|>]
$\endgroup$
7
  • 1
    $\begingroup$ Row is a protected built-in symbol in Mathematica, you can't use it as a variable. Please write down the output you are trying to achieve, i.e. what the final Association should look like. $\endgroup$
    – C. E.
    Commented Jul 16, 2015 at 16:10
  • 10
    $\begingroup$ Well, the obvious way is Dataset@AssociationThread[row, AssociationThread[col, #] & /@ tbl] ... I'm waiting to see better ways as I find this too long. $\endgroup$
    – Szabolcs
    Commented Jul 16, 2015 at 16:27
  • $\begingroup$ I made corresponding edits. Thanks! $\endgroup$
    – BenP1192
    Commented Jul 16, 2015 at 16:27
  • 2
    $\begingroup$ The best (bulletproof) way to avoid conflicts with builtin symbols is to start your own symbol names with lowercase letters. $\endgroup$
    – Szabolcs
    Commented Jul 16, 2015 at 16:35
  • 1
    $\begingroup$ this is pretty long too: Dataset[tbl][All, AssociationThread[col, Range[Length[col]]]] $\endgroup$
    – chuy
    Commented Jul 16, 2015 at 16:53

1 Answer 1

9
$\begingroup$

Might as well give an answer (might not be the ideal solution):

col = {"ColA", "ColB", "ColC"};
row = {"Row1", "Row2", "Row3"};
tbl = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

Dataset[AssociationThread[row, tbl]][All, AssociationThread[col, Range[Length[col]]]]

dataset

$\endgroup$
1
  • 3
    $\begingroup$ I actually like @Szabolcs' answer in the comments much better $\endgroup$
    – chuy
    Commented Jul 16, 2015 at 17:47

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.