4
$\begingroup$

Using the code, where ds is data formatted into a Dataset

GroupBy[ds, First] // TableForm

I get a table that I wanted, but I was wondering if I could somehow use the header of my dataset to designate which column to group by.

I just want to guard against a file generating some data and the first column not being the one I want to group my data by.

If we call the name of the column "name", I would like to do something to the tune of

GroupBy[ds, name] // TableForm
$\endgroup$
2
  • $\begingroup$ ds[GroupBy[#name&]] or GroupBy[#name&][ds] or GroupBy[ds, #name&]? $\endgroup$
    – kglr
    Commented Feb 20, 2015 at 16:55
  • $\begingroup$ Ahh ds[GroupBy[#name&]] works! Thanks! $\endgroup$ Commented Feb 20, 2015 at 16:57

2 Answers 2

3
$\begingroup$
ds[GroupBy[#name&]] (* or *)
GroupBy[#name&][ds] (* or *)
GroupBy[ds, #name&]
$\endgroup$
2
$\begingroup$

Here is another form that may be a bit easier to work with than the Slot form in kguler's answer:

ds = 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" -> {}|>}]

ds[GroupBy["b"]]

enter image description here

You could also use Extract:

ds ~GroupBy~ Extract["b"]

In either case if the name is not a string add Key.

$\endgroup$
2
  • $\begingroup$ Ah I see, yes the headers are strings, ds[GroupBy[Key["b"]]] worked as well. Thanks for the syntax lesson Mr.Wizard!...somehow this eluded me in the mathematica documentation center definition for GroupBy $\endgroup$ Commented Feb 20, 2015 at 19:39
  • $\begingroup$ Ahh it does say that too, albeit not as clearly, I must have been reading too fast $\endgroup$ Commented Feb 20, 2015 at 19:58

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.