9
$\begingroup$

I would like to group the elements of row c of the following dataset according to the values in the columns a and b. That is

Go from here

dataset2

To here

grp

And then I would like to print this on a grid, without visible lists (like {2,7})

    1      2
 x  1      4
 y  2 
    7  
 z  7      8

Code

This is the dataset I used

dataset2 = Dataset[{
<|"a" -> 1, "b" -> "x", "c" -> 1|>,
<|"a" -> 1, "b" -> "y", "c" -> 2|>,
<|"a" -> 1, "b" -> "z", "c" -> 7|>,
<|"a" -> 2, "b" -> "x", "c" -> 4|>,
<|"a" -> 1, "b" -> "y", "c" -> 7|>,
<|"a" -> 2, "b" -> "z", "c" -> 8|>}]

and this is the dataset2 after grouping on columns a an b

grp = Dataset[{<|"b" -> "x", "a=1" -> {1}, 
"a=2" -> {4}|>, <|"b" -> "x", "a=1" -> {2, 7}, 
"a=2" -> {}|>, <|"b" -> "x", "a=1" -> {7}, "a=2" -> {8}|>} ]

Example from the help

that comes close to what I want to do

dataset = Dataset[{
<|"a" -> 1, "b" -> "x", "c" -> {1}|>,
<|"a" -> 2, "b" -> "y", "c" -> {2, 3}|>,
<|"a" -> 3, "b" -> "z", "c" -> {3}|>,
<|"a" -> 4, "b" -> "x", "c" -> {4, 5}|>,
<|"a" -> 5, "b" -> "y", "c" -> {5, 6, 7}|>,
<|"a" -> 6, "b" -> "z", "c" -> {}|>}]

dataset

dataset[GroupBy[Key["b"]], Catenate, "c"]
$\endgroup$
4
$\begingroup$

I don't understand the intermediate output that you want as you did not give it in Dataset form, but I believe the grouping you want can be done with this:

ds = dataset2[GroupBy[{#b &, #a &}], All, All, Extract["c"]];

ds // Normal
<|"x" -> <|1 -> {1}, 2 -> {4}|>, "y" -> <|1 -> {2, 7}|>, "z" -> <|1 -> {7}, 2 -> {8}|>|>

From there you might use something like this:

TableForm[
  ds[Values, Values] // Normal,
  TableHeadings -> {Normal @ Keys[ds], {1, 2}}
]

enter image description here


Correction; this part of my code is wrong:

ds[Values, Values] // Normal

It merely happens to work for the example given but if the "y" group had been under 2 it would be wrong. I can't think of a clean way to solve this, and what want to use doesn't work, I think because of this bug:

Hopefully WReach will stop by and give is a workaround. :-)

$\endgroup$
  • 1
    $\begingroup$ You can correct the problem you describe by replacing ds[Values, Values] with this ugliness: ds[Values /* (KeyUnion[#, {} &] &)][All, Values]. It fills in absent keys, ensuring that the columns "line up". This could all probably be baked into a single query but I, like you, am not sure what to make of that intermediate result. Oh, and I'm sure that we'd also run into the operator-form bug you reference. The type information in ds is messed up as written, but it can be fixed up by changing the GroupBy operator form to an explicit function (GroupBy[#, ...]&). $\endgroup$ – WReach Aug 30 '14 at 5:32

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.