3
$\begingroup$

Given a simple dataset like this one:

Mathematica graphics

...I want to apply some reduction function (like Total or MinMax) to each column separately, so that the result would be a one-row dataset, with the same number and names of columns as in the original dataset.

For example, if the reduction function were Total, the desired result would be

Mathematica graphics

For MinMax it would be

Mathematica graphics

&c.


Does the built-in Dataset functionality directly support this type of operation? Or does one have to unpack the Dataset, apply the reductions to the columns in the underlying data, and stuff the results in a new Dataset?

NB: If the former is the case, I'm looking for more than an incantation here. I want also to understand how the proposed solution follows from the Dataset syntax given in the documentation.


FWIW, the code I used to create the data dataset is given below.

data = Module[
  {
      numberOfRows = 8
   , columnNames = {"A", "B", "C", "D", "E"}
   , makeColumn
  }

  , SeedRandom[0]
  ; makeColumn[] := RandomReal[{0, 1}, numberOfRows]
  ; Dataset[Transpose[Association[# -> makeColumn[] & /@ columnNames], AllowedHeads -> All]]
]
$\endgroup$
  • $\begingroup$ Have you tried data[All,Total] ? $\endgroup$ – alancalvitti May 16 '16 at 2:53
  • $\begingroup$ @alancalvitti: Yes. It doesn't do the job. $\endgroup$ – kjo May 16 '16 at 3:00
  • $\begingroup$ Forgot Transpose - posted as answer below. $\endgroup$ – alancalvitti May 16 '16 at 4:12
4
$\begingroup$

For Total, this suffices:

data[Total /* List]

but for a general approach that also works with MinMax, try:

data[Transpose][List, Total]

and

data[Transpose][List, MinMax]

$\endgroup$
  • $\begingroup$ Thanks. For Total, the results for both your incantations match the desired result given in the question, but the result for the MinMax one doesn't. (I'm using v. 10.4.0.0.) $\endgroup$ – kjo May 16 '16 at 11:27
  • $\begingroup$ @kjo, the issue with MinMax is a limitation of Dataset formatting. Try Normal to look at the underlying Association. $\endgroup$ – alancalvitti May 16 '16 at 14:36
  • $\begingroup$ Thanks. After I wrote my comment I figured something related to formatting was afoot. I posted a question about it. $\endgroup$ – kjo May 16 '16 at 14:41
4
$\begingroup$

You may use Merge.

datMinMax = data[Merge[MinMax]];
datMinMax["A"]
(* {0.238452, 0.976188} *)

datTotal = data[Merge[Total]];
datTotal["B"]
(* 4.32817 *)

Hope this helps.

$\endgroup$

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.