TransWikia.com

How can I make a dataset with one element display with a header row?

Mathematica Asked on June 2, 2021

I’m building a virtual lab exercise in Mathematica. As part of it, I’m using Dynamic to show the students’ lab dataset that they store in memory using a ClickPane. However, I’m running into a quirk of Mathematica’s default formatting that isn’t ideal.

Specifically: Mathematica displays Datasets differently when they contain one element (MM 12.0):

ds1 = Dataset[{<|"a" -> 0.5, "b" -> 2.0|>}]
ds2 = Dataset[{<|"a" -> 0.5, "b" -> 2.0|>, <|"a" -> 1.0, "b" -> 3.14159|>}]

enter image description here

Is there a way to get Mathematica to display a one-element dataset like ds1 with the keys as a header row and the values as a data row, rather than in columns?

Ideally this would be deployable inside a Dynamic block, so that the displayed data tables would smoothly grow as the students "collected more data". In other words, if we did code such as

Dynamic[ (* something involving a variable ds *) ]
ds = ds1;

and then

ds = ds2;

the Dynamic display would in both cases show a two-column table with a header row followed by one row for each data point.

One Answer

At some point it is worth writing own UI from scratch:

ClearAll[DatasetTable];
DatasetTable[ds : Verbatim[Dataset][{KeyValuePattern[{}] ..}, ___]] :=
  Module[{union = KeyUnion@Normal[ds], keys, values}
  , keys = Keys@First@union
  ; values = Values@union
  ; Grid[
      Prepend[keys]@values
    , Frame -> All, FrameStyle -> [email protected]
    , Alignment -> Left
    , Background -> {{}, {[email protected]}}
    , Spacings -> {2, 1}
   ]
  ]
ds = ds1;
Dynamic @ DatasetTable @ ds

enter image description here

ds = ds2;

enter image description here

Correct answer by Kuba on June 2, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP