4
$\begingroup$

Is this the most idiomatic way to convert matrix into dataset? (for Mathematica 10 or higher)

I was kind of hoping this would work:

Dataset[{{"a", "b", "c"}, {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}}]

but it did not, instead I had to use this trick, the 4th line is a pretty arcane incantation:

m = {{"a", "b", "c"}, {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}}
data = Drop[m, 1]
columnNames = First[m]
as = AssociationThread[columnNames -> #] & /@ data
Dataset[as]

Is there no way around it? I would have expected with guides like this that imply Mathematica matrix/tables can be used in place of a spreadsheets, converting to a DataSet could be done in a single step (with some sort of in memory equivalent to SemanticImport that received a matrix instead of a file name, a "SemanticImportMatrix" equivalent to SemanticImportString)

Is there anything like that?

$\endgroup$
  • 2
    $\begingroup$ Dataset[AssociationThread[m[[1]] -> #] & /@ Rest[m]] is a bit shorter but it probably does not appeal to you either. Notice that the input is a matrix; thus, you have to add the addition structure (column titles) by hand. $\endgroup$ – Henrik Schumacher Feb 11 at 10:37
  • 2
    $\begingroup$ Currently, there is no better way to create a list of associations other than mapping AssociationThread over the matrix and I agree that this is a bit jarring. On the other hand: keep in mind that Dataset is not supposed to be a magical "turn everything into a nice data structure automatically" function: it's a wrapper that makes data easier to access and display (it also does some type checking in the background). Structuring your data is still a manual job. If a magic structuring function should be incorporated, it should be separate from Dataset, IMO. $\endgroup$ – Sjoerd Smit Feb 11 at 12:52
  • 1
    $\begingroup$ CSV and Excel formats have good support for interpretting the data as a dataset with headers using the "Dataset" and "HeaderLines" options.. I realize you have the data already in M though. I have honestly done a ImportString[ExportString[m, "CSV"], {"CSV", "Dataset"}, "HeaderLines" -> 1] as a workaround before, which works for this example. $\endgroup$ – GenericAccountName Feb 14 at 23:09

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.