4
$\begingroup$

After some calculations and a GroupBy I have a Dataset that is structured like this.

dat = Dataset@<|
   "Apples" -> 
    ConstantArray[Graphics[{Red, Rectangle[]}, ImageSize -> {300, Automatic}], 3],
   "Oranges" -> 
    ConstantArray[Graphics[{Orange, Rectangle[]}, ImageSize -> {300, Automatic}], 
     2],
   "Bananas" -> 
    ConstantArray[Graphics[{Yellow, Rectangle[]}, ImageSize -> {300, Automatic}], 5]
   |>

I now would like to apply a function to each of these rows that uses the row name in first row for for a Grid. However, I have been unable to figure out how to reference the row name using the dataset[All, f] query syntax as provided in the Dataset | Dataset Queries documentation.

I can do the Grid without the row name with:

dat[All, Grid[Partition[#, 2, 2, {1, 1}, ""]] &]

How do I reference the row name in the function? Is there some syntax of Keys that I should be using? I think not as Keys would give me the keys of the row columns. I'm looking for some sort of ParentKey function such that I could get the row's key for the grid. e.g.

dat[All,
 Grid[
   Join[ 
    {{ParentKey@#, SpanFromLeft}},
    Partition[#, 2, 2, {1, 1}, ""]
    ]] &]
$\endgroup$
  • $\begingroup$ On my 10.3 Mathematica automatically adds a column with the row names when executing your Grid code (because Dataset), just FYI. $\endgroup$ – Graumagier Nov 1 '15 at 20:16
  • $\begingroup$ @Graumagier Yes, that is correct; I too am on 10.3. What I would like to do is reference that "row" column in the function that is being mapped across the rows. It is a row indicator column. $\endgroup$ – Edmund Nov 1 '15 at 20:19
  • $\begingroup$ dat[KeyTake["Apples"], All]? $\endgroup$ – J. M. is in limbo Nov 1 '15 at 21:04
  • $\begingroup$ @J. M. Maybe something along the lines of dat[Grid@Transpose@{Keys@#, Values@#} &]? $\endgroup$ – Graumagier Nov 1 '15 at 21:29
  • $\begingroup$ @Grau, except that I have a feeling that this is doable without transposing... $\endgroup$ – J. M. is in limbo Nov 1 '15 at 21:34
2
$\begingroup$

Looking at the Associations guide in the documentation I came across KeyValueMap that can be applied to the entire table. Since the Dataset has named rows then the key will be the row name and the value will be the row.

dat[
  KeyValueMap[
   Function[{key, value},
    Grid[Join[{{key, SpanFromLeft}}, Partition[value, 2, 2, {1, 1}, ""]]]
    ]]
  ] // Normal

Now I can convert the notebook into a template notebook for reporting. :-)

$\endgroup$
  • $\begingroup$ Can also use Underscript in lieu of the 2nd part: dat[All, Grid[Partition[#, 2, 2, {1, 1}, ""]] &][ KeyValueMap[Underscript]] $\endgroup$ – alancalvitti Dec 7 '15 at 15:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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