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
  • $\begingroup$ ds[GroupBy[#name&]] or GroupBy[#name&][ds] or GroupBy[ds, #name&]? $\endgroup$ – kglr Feb 20 '15 at 16:55
  • $\begingroup$ Ahh ds[GroupBy[#name&]] works! Thanks! $\endgroup$ – justabeginner Feb 20 '15 at 16:57
ds[GroupBy[#name&]] (* or *)
GroupBy[#name&][ds] (* or *)
GroupBy[ds, #name&]
| improve this answer | |

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


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.

| improve this answer | |
  • $\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$ – justabeginner Feb 20 '15 at 19:39
  • $\begingroup$ Ahh it does say that too, albeit not as clearly, I must have been reading too fast $\endgroup$ – justabeginner Feb 20 '15 at 19:58

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.